Mongoose/Mongodb: Exclude fields from populated query data

后端 未结 4 625
灰色年华
灰色年华 2020-12-31 03:31

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

Author
.findOne({personcode: co         


        
相关标签:
4条回答
  • 2020-12-31 03:37

    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});
    
    0 讨论(0)
  • 2020-12-31 03:41

    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.

    0 讨论(0)
  • 2020-12-31 03:41

    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

    0 讨论(0)
  • 2020-12-31 04:01

    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
    
    0 讨论(0)
提交回复
热议问题