简体   繁体   中英

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

I need to check if there is a field content exisiting by the document id and the nested element which will be identified also by an id.

Therefore I take the document by Collection.findOne({ _id: 'dZXr2Pg7Ak4M5aYWF'}) , which gives me this:

{
    "_id" : "dZXr2Pg7Ak4M5aYWF",
    "points" : [
        {
            "id" : "Gwf5BzorXyYBZSEzK",
            "coordinates" : [
                433,
                215
            ],
            "content" : "anything"
        },
        {
            "id" : "iwSM98W5PD87BtcLa",
            "coordinates" : [
                666,
                186
            ]
        }
    ]
}

No I need to check if there is a content field for the given id , that means:

id = 'Gwf5BzorXyYBZSEzK' -> true
id = 'iwSM98W5PD87BtcLa' -> false

I also tried to get this information directly by findOne :

Collection.findOne({ 
    _id: 'dZXr2Pg7Ak4M5aYWF', 
    points: { 
        id: id, 
        content: { $exists: true } 
    } 
});

But this gives me just undefined .

Collection.findOne({ _id: 'dZXr2Pg7Ak4M5aYWF', }).points.filter(function (obj) { 
    return obj.id == id; 
})[0]).content ? true : false;

An example would be:

Collection.findOne({_id: 'dZXr2Pg7Ak4M5aYWF'},function(err, doc) {
    if (doc.points.content){
        console.log(true);
    } else {
        console.log(false);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM