【发布时间】:2017-02-16 16:57:39
【问题描述】:
我在 MongoDB 中有一个非常简单的数据库,其中一部分包含在用户和游戏中。像这样的:
const GameSchema = new Schema({
mode: Number
});
const UserSchema = new Schema({
username: String,
games: [{
type: Schema.Types.ObjectId,
ref: 'game'
}]
});
所以现在当我创建游戏时,我还想更新游戏中的用户,添加 _id。例如,如果我创建了一个 _id 为 778 的游戏,而该游戏由 _id 为 111 和 222 的用户玩,那么这些用户的游戏属性将更新为添加 778。
在给定的时间内,同一个用户可能正在玩不同的游戏,因此用户游戏会不断发展,游戏:[778] => [778,889] => [778,889,901] 等等...
为此,我正在使用 Mongoose 中间件。
GameSchema.post('save', function(doc, next) {
const User = mongoose.model('user');
Game.findById(doc._id)
.populate('players')
.then(game => {
let userIds = // retrieve the ids of the users playing the game
if (userIds.length) {
User.update(
{ _id: { $in: userIds } },
{ $push: { games: this._id } },
{ safe: true, multi: true }
)
.then((data) => {
console.log('updated users', data);
// here it says that both users were updated
next();
});
} else {
next();
}
});
});
问题是,游戏可以有 2 名玩家或 1 名玩家,在最后一种情况下,这很好用,但是当有 2 名用户要更新时,它不会更新游戏来添加新值,它基本上会覆盖整个数组,所以它是 [778] => [889] => [901]。
谁能帮助我或给我一个提示,我可以检查什么以了解发生了什么?
谢谢!
【问题讨论】: