JS/MongoDB:检查对象(集合文档)中是否存在嵌套字段

JS/MongoDB: Check if nested field is existing in a object (collection document)

本文关键字:是否 存在 字段 嵌套 文档 集合 MongoDB 检查 对象 JS      更新时间:2023-09-26

我需要检查文档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);
    }
});