I have a NodeJS application with Mongoose ODM. I want to select three particular fields from a collection. Example my collection is "Users" having fields '_id','username','email','usertype','password'... I want to select only 'username','email'&'usertype' . This was my code
var query = models.User.find({}).select('UserName', 'Email', 'UserType');
This was working fine with mongoose 2 version,I updated to Mongodb 2.2 and Mongoose 3.3.1. Now I am getting error
500 TypeError: Invalid select() argument. Must be a string or object.
Can anyone please suggest a solution?
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
select() is a method of Mongoose that is used to select document fields that are to be returned in the query result. It is used to include or exclude document fields that are returned from a Mongoose query. The select() method performs what is called query projection.
The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).
Getting Started. You need at least 2 parameters to call findOneAndUpdate() : filter and update . MongoDB finds the first document that matches filter and applies update . By default, findOneAndUpdate() returns the document as it was before MongoDB applied update .
Since mongoose 3 select() parameter can be either:
-
before fields that need to be excluded) So you should either use:
var query = models.User.find({}).select('UserName Email UserType');
or
var query = models.User.find({}).select({UserName : 1, Email : 1, UserType: 1});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With