Igor P.
Igor P.

Reputation: 1477

Mongoose/Mongodb: Exclude fields from populated query data

I use the following mongoose query in a MEAN-environment to find and output a particular author and his corresponding books.

Author
.findOne({personcode: code})
.select('-_id')
.select('-__v')
.populate('bookids') //referencing to book documents in another collection (->array of bookids)
.select('-_id') //this doens't affect the data coming from the bookids-documents
.select('-__v') //this doens't affect the data coming from the bookids-documents
.exec(function (err, data) {
   //foo
});

I would also like to exclude the "_id" and "__v" fields from the populated data coming from the external documents. How can that be achieved?

Upvotes: 33

Views: 36415

Answers (4)

the_haystacker
the_haystacker

Reputation: 1625

To exclude individually

User.findOne({_id: userId}).select("-password")

To exclude using the schema

var userSchema = mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
    select: false,
  },
});

or this will also work

db.collection.find({},{"field_req" : 1,"field_exclude":0});

Upvotes: 12

zinoadidi
zinoadidi

Reputation: 194

I came searching for something slightly different. just in case someone needs same as me.

you can specify specific fields to auto-populate during creation of schema as shown below

const randomSchema = mongoose.Schema({
  name: {type: String,trim: true},
  username: {type: String,trim: true},
  enemies: { 
    type: ObjectId, 
    ref: randomMongooseModel, 
    autopopulate:{
      select: '-password -randonSensitiveField' // remove listed fields from selection
    }
  },
  friends: { 
    type: ObjectId, 
    ref: randomMongooseModel, 
    autopopulate:{
      select: '_id name email username' // select only listed fields
    }
  }

});

I am using mongoose-autopopulate plugin for this example

Upvotes: 1

Ninja Coding
Ninja Coding

Reputation: 1404

Thanks JohnnyHK, and for object parameter this works:

Entity.populate({
    path: 'bookids',

    // some other properties
    match: {
        active: true
    },
    // some other properties

    select: '-_id -__v' // <-- this is the way
}).then(...) // etc

Upvotes: 12

JohnnyHK
JohnnyHK

Reputation: 311835

The second parameter of populate is a field selection string, so you can do this as:

Author
  .findOne({personcode: code})
  .select('-_id -__v')
  .populate('bookids', '-_id -__v')
  .exec(function (err, data) {
    //foo
});

Note that you should combine your field selections into a single string.

Upvotes: 74

Related Questions