当玩家加入游戏时,我正在使用猫鼬将玩家推入猫鼬中的玩家阵列。我收到以下错误:
"Can't canonicalize query: BadValue unknown top level operator: $push"
这似乎是我如何格式化$ push的问题 我试着按照这个答案,不确定我的代码与它们的实现有何不同: pushing object into array schema in Mongoose
我有以下架构:
var GameSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.Mixed,
players: [{
username: String,
currentRound: Number
}],
// the number represents the qNumber in the questionData.js
// and also the round number for what the player is currently on
questions: [Number]
});
以及以下更新电话
var Game = mongoose.model('Game', GameSchema);
var updateGame = function(req,res,next){
Game.findByIdAndUpdate(
req.body.code,
{$push: {"players": {username: "hardcode", currentRound: 1}}},
{safe: true, upsert: true, new: true},
function(err, model){
if (err){
console.log("ERROR: ", err);
res.send(500, err);
}else{
res.status(200).send(model);
}
}
);
};
答案 0 :(得分:1)
哎呀,我总是在问完后找出解决方案。
事实证明,因为我覆盖了我的架构中的_id键,所以Game.findByIdAndUpdate不起作用。 相反,我使用了传递_id键的findOneAndUpdate:
Game.findOneAndUpdate(
{"_id":req.body.code},
{$push: {"players": {username: "hardcode", currentRound: 1}}},
{safe: true, upsert: true, new: true},
function(err, model){
if (err){
console.log("ERROR: ", err);
res.send(500, err);
}else{
res.status(200).send(model);
}
}
);