0

I am new in NoSQL database and I want to find a way to search all item in the array based on a key, for example : if we have this collection database.collection("col")

{
    "_id" : ObjectId("59389f763007e086bc310c73"),
    "messageIds" : [ 
        1, 
        2, 
        3, 
        4, 
        5
    ],
    "participants" : {
        "59389e953007e086bc310c36" : 0,
        "59389ea63007e086bc310c41" : 0
    },
    "type" : "f"
}

How to find all document that have the participants "59389e953007e086bc310c36" in node.js?

In MongoDb I can find out all items but

db.getCollection('conversations').find(
    {
        "participants.59389e953007e086bc310c36" : 
            {
                $exists: true
            }
    })

I can not do that in Node.js because it will not evaluate user_oid by value

user_oid = "participants."+user_oid;
    let criteria = {
        user_oid: { $exists: true }
    }

    console.log(criteria);
    database.collection(CONVERSATION_COLLECTION).find(criteria, (err,doc) => {
        console.log(doc);
        console.log;

    })
ADO R
  • 49
  • 1
  • 10
  • Of course you can. Basically you are either getting that value from 1.) Request input where it's going to be a string. 2.) The result of another operation where it is an `ObjectId` but it does have a `.toString()` method which "should" simply be called in the context of joining with a string. In case 2 you can even call `user_oid.toString()` explicitly. It's not a great pattern to have named keys, but there is nothing stopping you doing it. – Neil Lunn Jun 08 '17 at 12:58
  • Problem is that you should be doing `let criteria = {}; criteria["participants."+user_oid.toString()] = { $exists: true };` – Neil Lunn Jun 08 '17 at 13:01
  • Thanks it works ! – ADO R Jun 08 '17 at 13:15

1 Answers1

0

You can use [] to set field dynamically

let criteria = {};
criteria['participants.'+user_oid] = { $exists: true };

console.log(criteria);
database.collection(CONVERSATION_COLLECTION).find(criteria, (err,doc) => {
    console.log(doc);
    console.log;
});
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68