[英]JS/MongoDB: Check if nested field is existing in a object (collection document)
我需要检查文档 id 和嵌套元素是否存在字段content
,该元素也将由 id 标识。
因此,我通过Collection.findOne({ _id: 'dZXr2Pg7Ak4M5aYWF'})
获取文档,这给了我:
{
"_id" : "dZXr2Pg7Ak4M5aYWF",
"points" : [
{
"id" : "Gwf5BzorXyYBZSEzK",
"coordinates" : [
433,
215
],
"content" : "anything"
},
{
"id" : "iwSM98W5PD87BtcLa",
"coordinates" : [
666,
186
]
}
]
}
不,我需要检查给定id
是否有content
字段,这意味着:
id = 'Gwf5BzorXyYBZSEzK' -> true
id = 'iwSM98W5PD87BtcLa' -> false
我还尝试通过findOne
直接获取此信息:
Collection.findOne({
_id: 'dZXr2Pg7Ak4M5aYWF',
points: {
id: id,
content: { $exists: true }
}
});
但这给了我undefined
。
Collection.findOne({ _id: 'dZXr2Pg7Ak4M5aYWF', }).points.filter(function (obj) {
return obj.id == id;
})[0]).content ? true : false;
一个例子是:
Collection.findOne({_id: 'dZXr2Pg7Ak4M5aYWF'},function(err, doc) {
if (doc.points.content){
console.log(true);
} else {
console.log(false);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.