如何使用mongoose填充id数组?

时间:2018-01-02 11:40:54

标签: node.js mongodb mongoose

我尝试填充对象IDS数组,但它没有工作

Mongoose对象

const Schema = mongoose.Schema;

const OrderSchema = new Schema({
  products: [{
    product: { type: Schema.Types.ObjectId, ref: 'Product'},
    quantity: { type: Number, default: 1},
    price: { type: Number, default: 0},
  }],
});

let Model = mongoose.model('Product', ProductSchema);
module.exports = Model;

获取所有订单的API路线

const Order = require('../models/order');

router.get('/orders', checkJWT, (req, res, next) => {

    Order
    .find({ owner: req.decoded.user._id })
    .populate('products.product')
    .exec((err, orders) => {
      res.json({
        orders: orders
      });
    });
  })

它仍然显示产品的ID

"products": [
                {
                    "_id": "5a47b6c35e96e3900fd63984",
                    "price": 0,
                    "quantity": 2
                }
            ]

1 个答案:

答案 0 :(得分:0)

替换

type: Schema.Types.ObjectId;

type: mongoose.Schema.Types.ObjectId;