【问题标题】:Mongoose/Mongodb: Exclude fields from populated query dataMongoose/Mongodb:从填充的查询数据中排除字段
【发布时间】:2015-01-10 23:11:39
【问题描述】:

我在 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”字段。如何实现?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    populate的第二个参数是一个字段选择字符串,所以你可以这样做:

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

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

    【讨论】:

    • 我们还可以填充多个 refs,然后使用 excluder 参数将从所有填充的模式中排除字段Author .findOne({personcode: code}) .select('-_id -__v') .populate('bookids shelfId rowId', '-_id -__v') .exec(function (err, data) { //foo });
    【解决方案2】:

    单独排除

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

    【讨论】:

      【解决方案3】:

      感谢 JohnnyHK,对于对象参数,此方法有效:

      Entity.populate({
          path: 'bookids',
      
          // some other properties
          match: {
              active: true
          },
          // some other properties
      
          select: '-_id -__v' // <-- this is the way
      }).then(...) // etc
      

      【讨论】:

        【解决方案4】:

        我来寻找一些稍微不同的东西。以防万一有人需要和我一样。

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

        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 插件

        【讨论】:

          猜你喜欢
          • 2012-07-15
          • 2021-04-19
          • 2019-10-19
          • 2013-07-06
          • 1970-01-01
          • 2021-03-03
          • 2019-02-08
          • 2013-11-03
          • 2021-11-03
          相关资源
          最近更新 更多