猫鼬由子文档ObjectId填充

时间:2019-09-03 20:03:24

标签: node.js mongodb express mongoose aggregation

我一直在尝试用某些交货填充订单,这些交货作为子文档存储在产品中。现有的答案似乎都无法解决我的确切问题,尽管感觉它应该解决几乎所有在对象中使用子文档的人。

基本上我想做的是让用户显示他的所有订单,这应该通过product.deliveries []的order.deliveryId填充数据。

我尝试用populate查找,在使用子文档_id时似乎不起作用(在使用产品_id时有效,但会返回所有交货)

我已经非常接近聚合和查找+项目和过滤器,但是问题是: 1.使用子项_id查找返回包括所有子项文档的父对象 2.尝试使用_id过滤单个所需的子文档不起作用,因为对_id进行过滤根本不起作用。我已经设法在ObjectId上使用$ toString使其在mongo shell中起作用,但这似乎也不在mongoose中起作用。

// Order schema

var Order = new Schema({
    buyerId: {type: Schema.Types.ObjectId, ref: 'User'},
    deliveryId: {type: Schema.Types.ObjectId, ref: 'Product.Stock'},
    order_date: {type: Date, default: Date.now}
});

// Product with nested Delivery schema

var Delivery = new Schema({
    supplierId: {type: Schema.Types.ObjectId, ref: 'User', required: true},
    created_on: {type: Date, default: Date.now},
    amount_supplied: {type: Number, required: true, min: 1},
    amount_left: {type: Number, required: true, min: 0},
    price: {type: Number, required: true, min: 1}
});

var Product = new Schema({
    displayName: {type: String, required: true},
    description: {type: String, required: true},
    imagePath: {type: String, required: true},
    deliveries: [Delivery]
});

// User schema

var User = new Schema({
    oid: {type: String, required: true},
    displayName: {type: String, required: true},
    email: {type: String, required: true}
});

// Query to obtain data

Order.aggregate([
        { $match: { 'buyerId': req.user._id} },
        { $sort: { '_id': -1 } },
        { $lookup: { from: 'products', localField: 'deliveryId', foreignField: 'deliveries._id', as: 'productInfo'} },
        { $unwind: '$productInfo'},
        { $project: {
            _id: 1,
            buyerId: 1,
            deliveryId: 1,
            order_date: 1,
            productName: '$productInfo.displayName',
            deliveryInfo: { $filter: {
                input: '$productInfo.deliveries',
                as: 'Object',
                cond: { $eq: ['$$Object._id', '$deliveryId' ] }
            }}}}
    ], function (err, docs) {
        res.render('orders', { title: 'Orders | Fridge', orders: docs, user: req.user });
    });

预期结果将是对象,包括特定的交付详细信息,尤其是价格和供应商,因为它随交付而变化。 (现在它不匹配任何内容,因为_id上的匹配不起作用。其他文章建议使用mongoose.Types.ObjectId()强制转换_id,但这仅在从node.js代码中强制转换值时有效,而在匹配时无效文档中的mongo值。)

{
    _id:5d6d688b78899416069b9166
    buyerId:5d5b0de20d705f0a341f793c
    stockId:5d658f92f656e02e107b6f13
    order_date:2019-09-02T19:07:55.352+00:00
    productInfo:"BigShock Zero"
    deliveryInfo:Array
        0:Object
        _id:5d658f92f656e02e107b6f13
        supplierId:5d5b0de20d705f0a341f793c
        amount_supplied:40
        amount_left:37
        price:4

}

0 个答案:

没有答案