node.js - 如何在 mongoDB 中添加、更新、删除嵌套对象
问题描述
我是 mongoDB 和后端的新手。我有一个嵌套的 MongoDB 模型模式。我需要更新、删除和添加该嵌套对象/数组。我怎样才能做到这一点 ?
如何从列数组和恢复数组中删除/添加/更新项目。
const userSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
},
columns: [
{
title: {
type: String,
required: true,
},
resumes: [
{
name: {
type: String,
required: true,
},
resume: {
type: String,
required: true,
},
},
],
},
],
});
const Users = mongoose.model('Users', userSchema);
这是我的架构
解决方案
要将新项目添加到列数组:
let newData = {title: "New Title", resumes: []}
let userData = await User.findByIdAndUpdate(userID, {
$push: {
columns: newData,
},
});
要将新项目添加到列内的 resumes 数组中:
let newData = {name: "New Name", resume: "New Resume"}
let userData = await User.updateOne(
{
_id: mongoose.Types.ObjectId("60f54774761788cd80f56xxx"),
"columns._id": mongoose.Types.ObjectId("60f54774761788cd80f56xxx"),
},
{
$push: { "columns.$.resumes": newData },
}
);
同样,您可以使用$pull
运算符从数组中删除一个对象,并$(update)
更新数组中的元素
推荐阅读
- powershell - 如果用户存在于两个对象中,则从对象 1 [Powershell] 返回其值
- python - Selenium Web 抓取没有 id 或类名的嵌套 div
- haskell - 惰性评估是如何以不需要比所产生的收益更多的开销的方式实现的?
- python - pandas - 访问数据框中前一行的值
- javascript - 使用 replace() 但我不需要原始字符串
- reactjs - “gatsby-node.js”在运行 onCreateNode 生命周期时抛出错误:fmImagesToRelative is not a function
- json - 如何使用 Swift 代码 4 使用 JSON 解码器构建模型和解析
- django - django-modeltranslation:如何禁用显示没有翻译的语言的对象(例如帖子)?
- angular - 带有查询参数的角度路由不起作用
- r - 使用 ggcorrplot2 的 R 相关图:“x 轴”标签被裁剪