[英]How can i add, update, delete nested objects in mongoDB
I'm new to mongoDB and backend stuffs.我是 mongoDB 和后端的新手。 I've a nested MongoDB model schema.
我有一个嵌套的 MongoDB 模型架构。 I need to update, delete and add in that nested objects/array.
我需要更新、删除和添加嵌套对象/数组。 How can I do that ?
我怎样才能做到这一点 ?
How can I delete/add/update item from columns array and resume array.如何从列数组和恢复数组中删除/添加/更新项目。
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);
This is my schema这是我的架构
To add new item to the columns array:将新项目添加到列数组:
let newData = {title: "New Title", resumes: []}
let userData = await User.findByIdAndUpdate(userID, {
$push: {
columns: newData,
},
});
To add new item to the resumes array inside columns:要将新项目添加到列内的 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 },
}
);
Similarly, you can use $pull
operator to remove an object from the array, and $(update)
to update the element inside the array同样,您可以使用
$pull
运算符从数组中删除一个对象,并使用$(update)
更新数组内的元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.