我有以下架构:
var Child = new mongoose.Schema({
'field': String,
'value': String
});
var Parent = new mongoose.Schema({
'name': String,
'children': [ Child ]
});
我想返回 Parent
,其中一个 Child
对应于以下 JSON 对象:
{ 'field': 'Family Name', 'value': 'Smith' }
我试过这个:
Parent.findOne({ 'children': { 'field': 'Family Name', 'value': 'Smith' } }, fn ...)
但它一直在检索 null
。
编辑:
通过Mongo shell扩展测试,我发现Child
子文档有自己的_id
。如果我将该 _id
添加到查询中,它会获取 parent
文档。现在,我事先不知道那个 child id
会是什么。那么:如何从子文档查询中删除它? (换句话说,上面的查询从字面上寻找一个只有两个属性的 JSON 对象,而子文档有三个)
我的环境是:Node.js、Mongoose、MongoDB
最佳答案
看来 $elemMatch
是解决这个问题的查询运算符。实际查询应该这样写:
Parent.findOne({ 'children': { $elemMatch: { 'field': 'Family Name', 'value': 'Smith' } } }, fn ...)
关于json - 如何根据 Mongoose 中的子文档值检索父文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686374/