Selecting specific fields in MongooseJs

I have a NodeJS application with Mongoose ODM. I want to select three separate fields from the collection. An example of my collection is "Users" with the fields "_id", "username", "email", "usertype", "password" ... I want to select only the username, 'email' and 'usertype'. That was my code.

var query = models.User.find({}).select('UserName', 'Email', 'UserType'); 

This worked fine with mongoose 2 version, I upgraded to Mongodb 2.2 and Mongoose 3.3.1. Now i get an error

 500 TypeError: Invalid select() argument. Must be a string or object. 

Can anyone suggest a solution?

+7
source share
2 answers

Since the mongoose 3 select () parameter may be as follows:

  • object containing 0-1 map of excluded / included fields
  • a line with space delimiters (with - before the fields 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}); 
+14
source

In Mongoose version 4, you do not need select ().

 var query = models.User.find({}, 'UserName Email UserType'); 
+10
source

All Articles