Selecting particular fields in MongooseJs


Question

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?

1
9
10/25/2012 9:03:15 AM

Accepted Answer

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});
16
10/25/2012 9:15:38 AM

As of Mongoose version 4, you don't need select().

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon