Mongoose/Mongodb:从填充查询数据中排除字段

30

在 MEAN 环境中,我使用以下 mongoose 查询来查找并输出特定作者及其相应的书籍。

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
});

我也想从外部文档中排除“_id”和“__v”字段的填充数据。如何实现?
4个回答

69
populate 的第二个参数是一个字段选择字符串,因此你可以这样做:
Author
  .findOne({personcode: code})
  .select('-_id -__v')
  .populate('bookids', '-_id -__v')
  .exec(function (err, data) {
    //foo
});

请注意,您应该将您的字段选择组合成单个字符串。


我们还可以填充多个引用,然后使用排除参数将字段从所有填充的模式中排除。例如:Author .findOne({personcode: code}) .select('-_id -__v') .populate('bookids shelfId rowId', '-_id -__v') .exec(function (err, data) { //foo }); - Shubham Shaw

11

谢谢JohnnyHK,对于对象参数,这个方法是有效的:

Entity.populate({
    path: 'bookids',

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

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

11

单独排除

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

排除使用模式

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

或者这个也可以运行

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

1

我正在寻找与众不同的东西。以防有人需要和我一样的东西。

您可以在创建模式时指定要自动填充的特定字段,如下所示:

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
    }
  }

});

我将使用mongoose-autopopulate插件作为示例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接