【问题标题】:Mongoose nested populate queryMongoose 嵌套填充查询
【发布时间】:2014-12-29 15:27:10
【问题描述】:

我正在尝试返回与特定用户 ID 相关联的优惠券列表并填充 _merchant 引用。

这个查询正确地填充了 _merchant 引用。如果我可以补充:

其中的 coupon.users.contains(myuserid) 到我的查询中会得到我需要的东西

db.couponModel.find().populate('_merchant').exec(function(err, coupons) { 
    res.send(coupons);
});

或者这个查询找到了我需要的正确优惠券。如果我可以补充:

populate(_merchant) 到我的查询中,这也会得到我需要的。

db.userModel.findById(req.params.id).populate('coupons').exec(function(err, user) {
    res.send(user.coupons)
});

架构

var userSchema = new Schema({
    email: { type: String, required: true , unique: true },
    coupons: [{ type: Schema.ObjectId, ref: 'Coupon' }]
});

var couponSchema = new Schema({
    _merchant: { type: Schema.ObjectId, ref: 'Merchant', required: true },
    couponid: { type: Number, required: true, unique: true },
    users: [{ type: Schema.ObjectId, ref: 'User' }]


});

var merchantSchema = new Schema({
    name: { type: String, required: true , unique: true }
    coupons: [{ type: ObjectId, ref: 'Coupon' }],

});

我需要混合这两个查询来获得我想要的结果。

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

使用 $all 选项解决了这个问题。这里的例子:https://github.com/LearnBoost/mongoose/blob/master/test/query.test.js#L396http://docs.mongodb.org/manual/reference/operator/all/#_S_all

最终查询代码:

db.couponModel.find({users: {$all:[req.params.id]}}).populate('_merchant').exec(function(err, coupons) { console.log(coupons); })

【讨论】:

    【解决方案2】:

    使用 $all 选项。 db.couponModel.find({users: {$all:[req.params.id]}}).populate('_merchant').exec(function(err, coupons) { console.log(coupons); })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 2015-04-08
      • 2020-06-07
      • 1970-01-01
      • 2019-12-06
      • 2014-10-27
      相关资源
      最近更新 更多