使用$ PUSH的更新在Mongoose Express 节点中不起作用



此代码正确地从API服务获取JSON数据,但不更新MongoDB中的嵌套文档,几乎尝试了Everthing

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

使用 $each with $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 
});

最新更新