2

Alright so in this original question i was trying to search by key name only and only outputting the value of that name i was able to do this by using .toArray() if i did not then i would get this huge output of irrelevant data. But then it's tedious in the callback to use the data because it was in a array when it's not supposed to be.

Some examples. What is the difference between these two. The former gives me a output with out the use of .toArray() and the latter if i remove the .toArray() i get irrelevant data as the output.

Former

collection.findOne({"username" : username}, function(err, result) {
            console.log(result);
            callback(err, result);
            db.close();
        });

Latter

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

Also why when more then one parameter is included i.e "credentials":1,"_id":0,"username":0 as in the original question a answer by user Alok Deshwal do you get the error.

MongoError: Can't canonicalize query: BadValue Projection cannot have a mix of inclusion and exclusion.

So i guess the bottom line is how do i achieve a output with out the use of .toArray()

Output I'm getting with .toArray().

[{
    _id: 5636e00c09431db4560ef063,
    credentials: {
        password: '120bfeae7386165304b1cce4755a5c509593cc9157f58bac9d6f03e2230421cf',
        randomSalt: '00dfb37635ba7e5a513f9fd6e8bdf746f85ec3571df8288e1fdb44f399e331f0'
    }
}]

Output i want.

{
    _id: 56378e258300a47301b151ed,
    credentials: {
        password: '05c9f953969c7478fab0c5495b50d356ae9205c62ff41bab4d7891b804c1f369',
        randomSalt: '09973bc8109a9f6255f63e96528f5cf8ef74248192c60121159781f5d1f5f264'
    }
}
Community
  • 1
  • 1
Darkrum
  • 1,325
  • 1
  • 10
  • 27

1 Answers1

3

That error means you can not mix inclusion and exclusion of keys(_id not considered). To be precise you can go on with

"credentials":0,"_id":0,"username":0

or

"credentials":1,"_id":0,"username":1

Mixing of inclusions and exclusions is not allowed.You can refer to https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/ for that. Coming to second part alternatives for cursor.toArray() are using next

cursor.next(function(err,result){
   if (result)
      //Returns the next document in a cursor.
})

or using each method as follows

cursor.each(function(err,result){
    if(result){
       //each document in cursor
    }
})
Vishnu gondlekar
  • 3,896
  • 21
  • 35