【问题标题】:Update with $PUSH is not working in Mongoose + Express + Node使用 $PUSH 进行更新在 Mongoose + Express + Node 中不起作用
【发布时间】:2018-07-30 03:45:08
【问题描述】:

此代码正确地从 API 服务获取 JSON 数据,但未更新 MongoDB 中的嵌套文档,几乎尝试过任何事情

 api.squad(matchid, function(datapack) { 
   var data = JSON.parse(datapack);

    for (var i = 0; i < data.squad.length; i++) {
      players = data.squad[i].players;

      for(var j = 0; j < players.length; j++){

        console.log(players[j]);  // Working Fine Till here , Data from api showing here in console

        var player = { pid: players[j].pid, name: players[j].name };
        squadModel.update(              
          { leagueId: leagueId }, 
          {$push: {players: player} }       // This Update is Not Working
        );

      }
    }
  });

代码的架构如下。

    // Squad Players  -- Sub Schema of Squad
var squadPlayersSchema = mongoose.Schema({
    pid:{
      type: Number,
      required: true
    },
    name:{
      type: String,
      required: true
    },
    type:{
        type: String,
    },
    cost:{
        type: Number,
    },
    country:{
        type: String,
    },
    status : {
        type:Boolean,
        default:false
    }
  });


// Squad Schema
var squadSchema = mongoose.Schema({

    leagueId:{
        type: mongoose.Schema.Types.ObjectId,
        ref :'leagueModel',
        required: true
    },
    players : [squadPlayersSchema],
    isLaunched : {
        type:Boolean,
        default:false
    }

});

var squads = module.exports = mongoose.model('squads', squadSchema);

请帮助这件事刚刚拒绝工作。更新查询在 MongoDB GUI Studio3T Shell 中运行良好

Studio3T 中运行的演示查询示例运行良好,但使用上面的代码更新文档却没有。

db.squads.update(
              { "leagueId": ObjectId("5a85900d8b3b30165875ff0d") }, 
              {
                "$push": {
                  "players":  { pid: 1234567, name: "Some Name" }
                }
              }
            );

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    使用 $each$addToSet,如下所示:

    api.squad(leagueId, datapack => { 
        const data = JSON.parse(datapack);
        let updates = []; // array to hold updates promises
    
        data.squad.forEach(squad => { // iterate the data.squad array to get the players list
    
            let promise = squadModel.findOneAndUpdate(              
                { leagueId: leagueId }, 
                { '$addToSet': { 'players': { '$each': squad.players } } },
                { 'upsert': true }
            ); // update operation as a promise
            updates.push(promise);
        });
    
        Promise.all(updates).then(console.log).catch(console.error); // resolves when all of the updates promises have resolved 
    });
    

    【讨论】:

    • 感谢您的宝贵时间,但不知何故在 $PUSH 后添加 {safe: true} 后跟一个逗号使其工作现在一切都按预期工作,也会尝试您的建议...... .i 如果您能说出这很安全:真实的事情以及为什么我的代码现在可以使用它,那就太好了。有趣的是,当我在 GUI 中运行这段代码时,它不需要这个 {safe:true} 东西。
    • 我从这篇博文中找到了解决方案:blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2018-08-25
    • 1970-01-01
    相关资源
    最近更新 更多