如何在猫鼬中填充模型

时间:2021-04-02 04:18:45

标签: node.js mongodb mongoose

当我向我的订单发送 GET 请求时,响应会在我的订单项中返回 OjectID。在我的情况下,如何填充模型以获取 orderItems 名称?与产品型号相关的我的订单项目。需要返回产品名称。我是 mongo db 的新手。不太了解 Mongo 中的填充方法

邮递员结果

[
    {
        "orderItems": [
            "60668d8514508746c5480ede"
        ],
        "status": "3",
        "_id": "60668d8514508746c5480edf",
        "shippingAddress1": "Lo",
        "shippingAddress2": "2/1",
        "city": "5",
        "zip": "5",
        "phone": "5633",
        "totalPrice": 700,
        "user": {
            "_id": "60644f8d87463d10b8c7bb27",
            "name": "Lopez",
            "id": "60644f8d87463d10b8c7bb27"
        },
        "dateOrdered": "2021-04-02T03:20:37.884Z",
        "__v": 0,
        "id": "60668d8514508746c5480edf"
    }
]

我的获取请求

router.get(`/`, async (req, res) =>{
    const orderList = await Order.find().populate('user', 'name').sort({'dateOrdered': -1});

    if(!orderList) {
        res.status(500).json({success: false})
    } 
    res.send(orderList);
})

模型

// Order Model
const orderSchema = mongoose.Schema({
    orderItems: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'OrderItem',
        required:true
    }],
orderSchema.virtual('id').get(function () {
    return this._id.toHexString();
});

orderSchema.set('toJSON', {
    virtuals: true,
});

exports.Order = mongoose.model('Order', orderSchema);

//Order Items Model

onst orderItemSchema = mongoose.Schema({
    quantity: {
        type: Number,
        required: true
    },
    product: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product'
    }
})

exports.OrderItem = mongoose.model('OrderItem', orderItemSchema);

1 个答案:

答案 0 :(得分:1)

<块引用>

订单 -> 订单项 -> 产品

选项 -1

Order.find().populate('user', 'name').populate({ path : 'orderItems', populate : { path : 'product' } })

https://github.com/Automattic/mongoose/issues/1377


选项 -2

https://mongoosejs.com/docs/populate.html

https://mongoosejs.com/docs/populate.html#populate-middleware

添加:-

const populateProduct = function(next) {
  this.populate('product');
  next();
};

orderItemSchema.pre('findOne', populateProduct).pre('find', populateProduct);

更改查询,如:-

Order.find().populate('user', 'name').populate('orderItems')

https://www.npmjs.com/package/mongoose-autopopulate