如何从Nodejs中另一个模式内引用的模式中填充mongoose模式值?

时间:2016-05-28 18:12:16

标签: node.js mongoose mongoose-populate

我有一个mongoose架构"产品"其中包括一系列颜色(另一种模式)。 订单架构包含用户和产品数组。产品包含产品,数量和颜色。这里的颜色是特定于产品的模式。

我希望用户能够订购特定颜色的产品(产品可用的颜色) 如何填充所选产品的颜色?

模型\ product.js

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var ColorSchema = new Schema({
    value : {type : String} 
});


var ProductSchema = new Schema({
    name:  {
        type: String,
     default: ''
    },
    colors : [ColorSchema] 
 });

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

 module.exports = mongoose.model('Color', ColorSchema );

模型\ order.js

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var OrderSchema = new Schema({
    timestamp : { type: Date, default: Date.now },
    user : {type: mongoose.Schema.Types.ObjectId, ref: 'User'} ,
    products : [{
        product : {type: mongoose.Schema.Types.ObjectId, ref: 'Product'},
        color :  {type: mongoose.Schema.Types.ObjectId, ref: 'Color'},
        quantity : Number
        }]

});


module.exports = mongoose.model('Order', OrderSchema );

获取查询:

function getOrders(res) {
    Order.find({})
    .populate('user')
    .populate('products.product')
    .populate('products.color')
    .exec(function (err, orders) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            //console.log("error");
            res.send(err);
        }
        res.json(orders); // return all orders in JSON format
    });

}

我已经使用postman将条目添加到数据库中。 get Query将颜色字段返回为null。

[
  {
    "_id": "5749b94508e742484c13d16e",
    "__v": 0,
    "user": {
          "_id": "57482af31d885d030064f6ff",
          "__v": 0,
          "phone": "9999999999",
          "name": "XYZ"
        },
    "products": [
      {
        "product": {
          "_id": "574957c3935ad71048593879",
          "__v": 0,
          "colors": [
            {
              "value": "Black",
              "_id": "574957c3935ad7104859387d"
            },
            {
              "value": "Gold",
              "_id": "574957c3935ad7104859387c"
            },
            {
              "value": "Silver",
              "_id": "574957c3935ad7104859387b"
            }
          ],
          "name": "Xiaomi mi Note 3"
        },
        "color": null,       // null if I put .populate('products.color')
        "quantity": 5,
        "_id": "5749b94508e742484c13d16f"
      }
    ],
    "timestamp": "2016-05-28T15:29:09.416Z"
  }
]

如果我删除.populate(' products.color'),它会返回产品中存在的颜色的ID。

用户和产品填写正常。问题仅在于颜色,因为它是从产品内部引用的。

[
  {
    "_id": "5749b94508e742484c13d16e",
    "__v": 0,
    "products": [
      {
        "product": {
          "_id": "574957c3935ad71048593879",
          "__v": 0,
          "colors": [
            {
              "value": "Black",
              "_id": "574957c3935ad7104859387d"
            },
            {
              "value": "Gold",
              "_id": "574957c3935ad7104859387c"
            },
            {
              "value": "Silver",
              "_id": "574957c3935ad7104859387b"
            }
          ],
          "name": "Xiaomi mi Note 3"
        },
        "color": "574957c3935ad7104859387b",  // <-- Id of silver color product if i remove .populate('products.color')
        "quantity": 5,
        "_id": "5749b94508e742484c13d16f"
      }
    ],
    "timestamp": "2016-05-28T15:29:09.416Z"
  }
]

我希望将颜色字段填充为:

"color": {
  "value": "Silver",
  "_id": "574957c3935ad7104859387b"
}

对此有何建议?

修改

添加订单的代码如下:

exports.addOrder = function (req, res) {

    var prods_arr = [];

    for(var i = 0, l = req.body.products.length; i < l; i++) {

        prods_arr.push({
            product: req.body.products[i].product,
            color: req.body.products[i].color,
            quantity: req.body.products[i].quantity
            })
        }   


    var order_obj = new Order();
    order_obj.user = req.body.user;
    order_obj.products = prods_arr;

    Order.create(order_obj, function (err, order) {
        if (err){
            res.send(err);
        }
        // get and return all the orders after you create another
        getOrders(res);
    });

};

使用Postman,我发送以下原始json数据作为请求的主体。

{
    "user": {
          "_id": "57482af31d885d030064f6ff",
          "__v": 0,
          "phone": "9999999999",
          "name": "XYZ"
        },
    "products": [
      {
        "product": {
          "_id": "574957c3935ad71048593879",
          "__v": 0,
          "colors": [
            {
              "value": "Black",
              "_id": "574957c3935ad7104859387d"
            },
            {
              "value": "Gold",
              "_id": "574957c3935ad7104859387c"
            },
            {
              "value": "Silver",
              "_id": "574957c3935ad7104859387b"
            }
          ],
          "name": "Xiaomi mi Note 3"
        },
        "color": {
              "value": "Silver",
              "_id": "574957c3935ad7104859387b"
            },       
        "quantity": 5,
      }
    ]
  }

0 个答案:

没有答案