Search code examples
node.jsmongodbmongoskinco-monk

Mongodb not returning specific fields


I am trying to return only one field sessions from a document.

I'm using the current query (it returns the entire document):

yield users.findOne({
    '_id': id // var id holds object id ObjectId("560ae1dc53cb3222679430f1")
}, {
    '_id': 0, // <--- being ignored
    'sessions': 1 // <--- being ignored
});

I tried in mongo shell and this works as it should:

db.users.find({"_id":ObjectId("560ae1dc53cb3222679430f1")},{"sessions":1,"_id":0}).pretty() // <--- works

I'm currently using co-monk which is based off of mongoskin. So it should work.


Solution

  • Not made clear in the documentation, but there is an explicit key name syntax to the "options" object :

    yield users.findOne({ '_id': id }, { 'fields': { '_id': 0, 'sessions': 1  }});
    

    So it works a bit differently to the MongoDB shell API. The same applies for other options such as sort.