此代码正在从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" }
}
}
);
答案 0 :(得分:0)
将 $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
});