Skip to content Skip to sidebar Skip to footer

Get Values By Key Name Mongodb Node.js Driver

I have looked every where and can not find whether it can be done I'm trying to return all values in a object by only searching by it's key name. My document looks like this. {

Solution 1:

You can do something like this in order to get existing credentials only.

var res = []; db.collection.find({credentials : {$exists:true}}).forEach(function(document){ res.push(document.credentials})

Then you can callback the array: callback(err, res)

Does this help you?

Solution 2:

Alright so based on what i original thought was the right way i can achieve my output by throwing it into a array. You only need "credentials":1 to only grab the credentials and including "credentials":1,"_id":0,"username":0 as told by Alok Deshwal causes mongodb to throw a error.

functiongetUserLoginFromDatabase(username, callback) {
    mongodb.connect(url, function(err, db) {
        if(err) {
                callback(err);
                db.close();
                return;
            }

        var collection = db.collection(username);

        collection.find({},{"credentials":1}).toArray(function(err, result) {
            callback(err, result);
            db.close();
        });
    });
};

But then it becomes tedious in the callback to use the data because it is in a array when it should not be. I'll be asking another question about this and also why including more fields causes mongodb to throw a error.

randomSalt = result[0]["credentials"].randomSalt;userStoredPassword = result[0]["credentials"].password;

Also the conclusion of this answer is here

Solution 3:

If you want to search by it's key name , you can use $exist operator

db.collection.find({},{"credentials":1,"_id":0,"username":0})

use "keyname":0 to exclude from result and "keyname":1 to include in result

Post a Comment for "Get Values By Key Name Mongodb Node.js Driver"