[英]How do I query an Id in an array? Mongoose
如何使用貓鼬查詢數組中的特定_id
這是代碼
var userSchema = new mongoose.Schema({
resume: {
educations: [{
school: String,
year: String
}]
}
});
如何特別查詢教育ID?
我的嘗試
User.findById({ 'resume.educations._id': req.body.education_id}, function(err, foundUser){
console.log(foundUser) --> Keep returning Undefined
});
已存儲的數據
console.log(req.body.education_id)
-> 5644318364acb9f1eb25c939
您可以將$ elementMatch與findOne一起使用,如下所示
User.findOne({'resume.educations': {$elemMatch: {_id: '564497eb366f59b004e9d17e'}}}, function(err, foundUser){
console.log(foundUser);
// output
// [ { resume: { educations: [ [Object] ] },
// __v: 0,
// _id: 564497eb366f59b004e9d17d } ]
});
這是我嘗試過的文件,它起作用了
{
"_id" : ObjectId("564497eb366f59b004e9d17d"),
"resume" : {
"educations" : [
{
"school" : "school name",
"year" : "1999",
"_id" : ObjectId("564497eb366f59b004e9d17e")
}
]
},
"__v" : 0
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.