简体   繁体   中英

Moogose append to the sub array document

I am having a problem with appending data into the sub 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');
    }
  );
};

This above code does append the data into the sub document, but however you can see the below output it appends a new item with a new index, which is not great. I kept my files model as files : Array any one can help? Much appreciated. the following json is what i have cut out from the document.

{
  "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"
  }
},

You are pushing an array into another, hence it is being nested.

If you want to append each item, use the $each operator:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM