如何在mongoose中保存objectID数组并添加字段?

时间:2017-06-25 23:17:27

标签: javascript node.js mongoose

我正试图在数组中保存以下内容......

我是通过POST发送的

req.body.products =

{id: "5936460d2fabd233f0ddaca3", buy: 30, cant:20},
{id: "5936460d2fabd233f2ddace6", buy: 25, cant:14}

该ID是现有产品的ObjectId

这是我的控制器

let facturaProv = new provBill({
  id_store: res.locals.store.id,
  name: req.body.name,
  category: req.body.category,
  products: req.body.products
});

facturaProv.save(function(err) {
  if (!err) res.send('OK')
  else res.send("error")
}
});

这是我的架构

provSchema: new Schema({
  id_store: { type: mongoose.Schema.Types.ObjectId, ref: 'store' },
  category:String,
  name: String,
  products: [{ type: mongoose.Schema.Types.ObjectId, ref: 'product' }]
})

如何修改架构以保存“买入”和“无法”字段?

我尝试了以下但不起作用:

products: [{ type: mongoose.Schema.Types.ObjectId, ref: 'product', buy: Number, cant:Number }]

感谢您的阅读和帮助。

2 个答案:

答案 0 :(得分:2)

修改架构如下:

products: [
  { 
     id : {type: mongoose.Schema.Types.ObjectId, ref: 'product'}, 
     buy: Number,
     cant: Number
  }
]

答案 1 :(得分:0)

这不是正确的JSON对象 system_time_zone +08 time_zone SYSTEM

请注意“”

{id: "5936460d2fabd233f0ddaca3", buy: 30, cant:20}, {id: "5936460d2fabd233f2ddace6", buy: 25, cant:14}