[英]How to update nested objects in MongoDb with Mongoose
[英]How can i add, update, delete nested objects in 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)
更新數組內的元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.