簡體   English   中英

Moogose追加到子數組文檔

[英]Moogose append to the sub array document

我在將數據附加到子文檔中時遇到問題。

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');
    }
  );
};

上面的代碼確實將數據附加到了子文檔中,但是您可以看到下面的輸出,它在新項目的后面附加了新索引,這並不好。 我將文件模型保存為files:Array誰能幫上忙? 非常感激。 以下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"
  }
},

您正在將一個數組推入另一個數組,因此它是嵌套的。

如果要附加每個項目,請使用$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');
    }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM