简体   繁体   English

猫鼬:你怎么不来?

[英]Mongoose: how do you unpopulate?

I'm using autopopulate , but there's one case where I don't want to populate. 我正在使用autopopulate ,但是在一种情况下,我不想填充。 How can I unpopulate? 我如何取消人烟?

var userSchema = new Schema({
  local: { type: ObjectId, ref: 'Local', autopopulate: true },
  facebook: { type: ObjectId, ref: 'Facebook', autopopulate: true },
  twitter: { type: ObjectId, ref: 'Twitter', autopopulate: true },
  google: { type: ObjectId, ref: 'Google', autopopulate: true }
});

User
  .findById(req.params.id)
  .unpopulate(local)
  .exec()...

As far as my understanding, mongoose-autopopulate is using mongoose middleware pre hook to configure the populate options on find and findOne queries before executing it. 据我了解,mongoose-autopopulate在执行之前使用mongoose中间件预挂钩在find和findOne查询上配置填充选项。 It is like implicitly attaching the populate option in the query. 这就像在查询中隐式附加populate选项。

For your schema, with mongoose-autopopulate User.findById(req.params.id) will get converted into 对于您的架构,使用猫鼬自动User.findById(req.params.id)将被转换为

User.findById(req.params.id).populate('local')
.populate('facebook').populate('twitter').populate('google');

And there is no way in mongoose-autopopulate to remove it, until and unless you explicitly disable the autopopulate option for the required field before querying. 在mongoose-autopopulate中无法删除它,除非并且除非您在查询前显式禁用了必填字段的autopopulate选项。

The populate function is nothing but an another call to the database to fetch the referenced document and embed it to the main document. populate函数不过是对数据库的另一个调用,以提取引用的文档并将其嵌入到主文档中。 So, try avoiding to populate it at first place and not removing it once you have already fetched it. 因此,请尽量避免首先填充它,并且一旦获取它就不要删除它。

See https://github.com/mongodb-js/mongoose-autopopulate/issues/7 . 参见https://github.com/mongodb-js/mongoose-autopopulate/issues/7

var numCalls = 0;
var optionsFunction = function() {
  ++numCalls;
  return false;
};

var bandSchema = new Schema({
  name: String,
  lead: { type: ObjectId, ref: 'people', autopopulate: optionsFunction }
});
bandSchema.plugin(autopopulate);

var Band = mongoose.model('band5', bandSchema, 'bands');
Band.findOne({ name: "Guns N' Roses" }, function(error, doc) {
  // `doc.lead` won't be populated because optionsFunction() is falsy
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM