如何在使用mongoose创建的用户集合中获取数组中的特定项


// database: db.getCollection('users').find({})
{
"_id" : ObjectId("60af81e943d991265c2b8746"),
"email" : "test@gmail.com.com",
"password" : "123456",
"notes" : [ 
{
"_id" : ObjectId("60af81e943d991265c2b8747"),
"title" : "test title",
"content" : "test content"
}
],
"__v" : 0
}
// userSchema
const userSchema = new mongoose.Schema({
email: String,
password: String,
notes: [{ title: String, content: String }],
});

///////////////////////////////////////////////////////////////////////////////////

app.post("/save", function (req, res) {
const idNote = req.body._id;
const userID = req.user._id;
User.findById({ _id: userID }, function (err, foundUser) {
if (err) {
console.log(err);
} else {
const notesArray = foundUser.notes;
}
}
console.log(notesArray);
})
});

现在,有没有一种方法可以获得特定的(user_id内部的notes_id(并使用它来查询文档(这样我就可以在用户内部找到特定的"notes"(,或者查询工作的唯一方法是寻找一个集合,其中唯一可以用来查询文档的道具是schema内部的道具?

如果我是对的。。。

const newTitle = req.body.title;
const newContent = req.body.content;
const userID = req.user._id;
User.findById({ _id: userID }, function (err, foundUser) {
if (err) {
console.log(err);
} else {
const notesArray = foundUser.notes;
const note = findNote(editNote, notesArray);
function findNote(editNote, notesArray) {
for (let i = 0; i < notesArray.length; i++) {
if (notesArray[i]._id == editNote) {
return notesArray[i];
} else {
console.log("not found!");
}
}
}
console.log(note);
}
});

我如何删除";注释";我需要编辑,然后创建一个NEW ONE+ALL数组的其余部分,并最终将新的注释数组推送到schema prop";注释":[],

{
"_id" : ObjectId("60af81e943d991265c2b8746"),
"email" : "test@gmail.com.com",
"password" : "123456",
"notes" : --> HERE <--,
"__v" : 0
}

如果我理解您的问题,您希望在特定用户属性的notes数组中添加/删除/编辑note对象。您只需一个查询就可以执行其中的任何操作。

添加新项目

如果您想为特定用户向notes数组中添加新项目,可以使用$push运算符,如下所示:

db.collection.update({
"_id": "user_1"
},
{
"$push": {
"notes": {
"_id": "note_5",
"title": "test title",
"content": "test content"
}
}
})

以下是工作示例:https://mongoplayground.net/p/AvRjSKZxNt7

删除项目

如果您想从特定用户的notes数组中删除项目,您可以使用$pull运算符来完成,如下所示:

db.collection.update({
"_id": "user_1"
},
{
"$pull": {
"notes": {
"_id": "note_4" 
}
}
})

以下是工作示例:https://mongoplayground.net/p/M_gS2T00PDS

编辑项目

如果您想为特定用户编辑notes数组中的项目,可以使用
position"操作员,像这样:

db.collection.update({
"_id": "user_1",
"notes._id": "note_4"
},
{
"$set": {
"notes.$.title": "This is new title"
}
})

以下是工作示例:https://mongoplayground.net/p/Gn9R5u2rBJd

最新更新