Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting particular fields in MongooseJs

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?

like image 745
dany Avatar asked Oct 25 '12 09:10

dany


People also ask

How do I select a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do you use Find and select in mongoose?

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.

What is __ V in MongoDB?

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 ).

How do you use findOneAndUpdate?

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 .


1 Answers

Since mongoose 3 select() parameter can be either:

  • an object containing 0-1 map of excluded/included fields
  • a space delimited string of fieldnames (with - 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});
like image 195
soulcheck Avatar answered Oct 05 '22 20:10

soulcheck