MongoDB查找然后查询嵌套文档



我正在尝试制作一个'喜欢'路由,通过_id查找用户,然后在对象 IDuser.post内部查询,到目前为止我尝试了这个:

User.find({
"_id": logged_user,
"posts_id": {
$elemMatch: req.body.id
}
}, (err, data) => {
if (err) {
res.json(err)
}
console.log(data);
})

图式:

username: String,
posts:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]

它返回一个空数组 '[]',如果它存在,我怎么能返回 true 的 false?

你用错$elemMatch。它需要一个对象。这样做:

User.find({"_id":logged_user,"posts":{$elemMatch: {$eq : req.body.id}}},(err,data)=>{ 
if(err){
res.json(err)
}
console.log(data);
)

最新更新