将元素推送到mongoose中的数组

时间:2018-04-09 21:21:09

标签: javascript node.js mongodb mongoose mean-stack

我正在尝试将元素推送到mongoose中的数组。我正在使用update和$ push。但它没有在数据库中更新它。这是我的代码。 routes.js:

    var Chooser = require('../chooser');

    var appRouter = function(app) {

    app.put("/chooser/:id", function(req, res) {
    console.log("ID: ", req.params.id);
    if (!req.body.toFollow) {
        return res.send({"status": "error", "message": "The account that you want to follow is needed"});
    }
    else {
        console.log("Cuenta: ", req.body.toFollow);
        Chooser.update({_id: req.params.id}, {$push: {accounts: {"name": "foo", "idAccount": 123456}}});
        return res.send({"status": "ok"});
    }

  });
}

这是我的猫鼬模式。 Chooser.js:

var mongoose = require('mongoose');

var chooserSchema = mongoose.Schema({
_id: Number,
accounts: [{name: String, idAccount: Number}]
}, { _id: false });

var Chooser = mongoose.model('Chooser', chooserSchema);

module.exports = Chooser;

4 个答案:

答案 0 :(得分:1)

据我所知,你必须这样做。

Model.findAndUpdate({_id: 'your_id'}, 
                    {$push: {'your_array_field': 
                    {"name": "foo","idAccount": 123456}}}, 
                    {new: true}, (err, result) => {
                    // Rest of the action goes here
                   })

答案 1 :(得分:0)

我们这样做 - 我们正在添加另一个模型,但在您的情况下,您只需添加一个数组,然后将其放入变量并代替req.body.resource ..

如果你不想,你也可以使用findByIdAndUpdate而不是Async。

这是模型元素:

 resources: [{type: mongoose.Schema.Types.ObjectId, ref: 'Resource'}],

这是将项添加到数组的方法:

//AddResource to a crew
export function addResource(req, res) {
  if (req.body._id) {
    delete req.body._id;
  }
  Crew.findByIdAndUpdateAsync(req.params.id,
    {
      $push: { "resources": req.body.resource }
    },
    { safe: true, upsert: true },
    function (err, model) {
      if (err) {
        //console.log(err);
        return res.send(err);
      }
      return res.json(model);
    });

并删除:

//deleteResource to a crew
export function deleteResource(req, res) {
  if (req.body._id) {
    delete req.body._id;
  }
  // console.log(req.body.resource);
  Crew.findByIdAndUpdateAsync(req.params.id,
    {
      $pullAll: { "resources": req.body.resource }
    },
    function (err, model) {
      // console.log(model);
      if (err) {
        //console.log(err);
        return res.send(err);
      }
      return res.json(model);
    });

答案 2 :(得分:0)

我们可以那样做

Model.findOneAndUpdate({"_id":req.body.id},{
            "$push": {"resources": req.body.resources}
        },{new: true, safe: true, upsert: true }).then((result) => {
            return res.status(201).json({
                status: "Success",
                message: "Resources Are Created Successfully",
                data: result
            });
        }).catch((error) => {
            return res.status(500).json({
                status: "Failed",
                message: "Database Error",
                data: error
            });
        });`

答案 3 :(得分:0)

这是更新猫鼬模型的方法(使用 async await ):


let updatedModel = await Model.findByIdAndUpdate(req.params.id,

 { $push: { accounts:{"name": "foo", "idAccount": 123456} } },

 { 'upsert': true });

或在您的代码中

如果您希望将更新后的文档退还给您,也许您错过了{new:true,upsert:true}。

Chooser.update({_id: req.params.id}, {$push: {accounts: {"name": "foo", "idAccount": 123456}}},{new: true, upsert: true });