Moogose附加到子数组文档

时间:2015-07-07 08:04:58

标签: mongodb mongoose

我在将数据附加到子文档时遇到问题。

exports.appendfiles = function(req, res) {
  project.findOneAndUpdate(
    { 
      _id: req.body.id 
    },
    { $push: 
      { 'files' : req.files }
    },
    {
      safe: true,
      upsert:true
    }, 
    function(err, data) {
      console.log(err);
      return res.send('ok');
    }
  );
};

上面的代码确实将数据附加到子文档中,但是你可以看到下面的输出它附加了一个带有新索引的新项目,这不是很好。我将我的文件模型保存为文件:数组任何人都可以提供帮助吗?非常感激。以下json是我从文档中删除的内容。

{
  "buffer": null,
  "truncated": false,
  "size": 497328,
  "extension": "csv",
  "path": "uploads/dc45dfeb54c4be89968faa46aabeb114.csv",
  "mimetype": "text/csv",
  "encoding": "7bit",
  "name": "dc45dfeb54c4be89968faa46aabeb114.csv",
  "originalname": "obansocial2015-04-20 (7).csv",
  "fieldname": "3"
},
{
  "0": {
    "buffer": null,
    "truncated": false,
    "size": 8855,
    "extension": "html",
    "path": "uploads/273bee3485fc564e80d80e92cef32215.html",
    "mimetype": "text/html",
    "encoding": "7bit",
    "name": "273bee3485fc564e80d80e92cef32215.html",
    "originalname": "Southern Stars Conference 2014.html",
    "fieldname": "0"
  },
  "1": {
    "buffer": null,
    "truncated": false,
    "size": 383631,
    "extension": "mp4",
    "path": "uploads/f32da61db7e8df6fccf97b65a788e39d.mp4",
    "mimetype": "video/mp4",
    "encoding": "7bit",
    "name": "f32da61db7e8df6fccf97b65a788e39d.mp4",
    "originalname": "video.mp4",
    "fieldname": "1"
  }
},

1 个答案:

答案 0 :(得分:2)

您正在将数组推入另一个数组,因此它正在嵌套。

如果要附加每个项目,请使用$each运算符:

project.findOneAndUpdate(
    { 
      _id: req.body.id 
    },
    { $push: 
      { 'files' : {$each: req.files} }
    },
    {
      safe: true,
      upsert:true
    }, 
    function(err, data) {
      console.log(err);
      return res.send('ok');
    }
);