使用Mongoosejs将数组添加到Mongodb

Adding array into Mongodb using Mongoosejs

本文关键字:Mongodb 添加 数组 Mongoosejs 使用      更新时间:2023-09-26

以下是我的两个模式:

var itemSchema = mongoose.Schema({
    body    : String
});
var taskSchema = mongoose.Schema({
    user_id    : { type: String, index: true }
  , short_id   : { type: String, index: true }
  , title      : { type: String, required: true }
  , desc       : String
  , items      : [itemSchema]
  , created_at : Date
});

从我的Angularjs应用程序,我可以成功地发布一个任务(包括其中的项目数组),但我有麻烦的项目插入到数据库。

我正在尝试这个

task.user_id = req.user.id;
task.short_id = '12345';
task.title = req.body.title;
task.desc = req.body.desc;
task.created_at = Date.now();
task.items.push({ body: req.body.items.body }); //note: body is also the one attribute of Item
下面是保存 的方法
task.save(function (err) {
  if (err) return res.send(400, err)
  res.send (task)
});

除了最后一行都可以工作-其他所有内容都被添加。我如何将项目数组添加到我的数据库中?

因为req.body.items是一个包含与itemSchema格式相同的项的数组,所以您可以直接赋值:

task.items = req.body.items;