【问题标题】:Push element to array in mongoose将元素推送到猫鼬中的数组
【发布时间】:2018-09-19 09:05:50
【问题描述】:

我正在尝试将元素推送到 mongoose 中的数组。我正在使用更新和 $push 来做这件事。但它没有在数据库中更新它。这是我的代码。 路线.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"});
    }

  });
}

这是我的猫鼬模式。选择器.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;

【问题讨论】:

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


【解决方案1】:

据我所知,您必须按照以下方式进行操作。

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

【讨论】:

    【解决方案2】:

    我们正在这样做 - 我们正在添加另一个模型,但在您的情况下,您只是添加一个数组,所以将它放在一个变量中并代替 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);
        });
    

    【讨论】:

      【解决方案3】:

      我们可以这样做

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

      【讨论】:

        【解决方案4】:

        这是在 mongoose 中更新模型的方法(使用 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 });
        
        

        【讨论】:

          猜你喜欢
          • 2018-05-10
          • 2019-10-13
          • 2019-03-22
          • 2021-08-29
          • 1970-01-01
          • 2016-01-29
          • 2015-02-12
          • 2017-10-03
          • 1970-01-01
          相关资源
          最近更新 更多