Mongoose/Mongodb: Exclude fields from populated query data

后端 未结 4 659
灰色年华
灰色年华 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: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

提交回复
热议问题