我正在使用Node.js和Mongoose。玩家和锦标赛变量是猫鼬对象,之前已获取。
我想将新的TournamentSession对象(不是Mongoose对象)添加到玩家对象的raceSessions字段中。我正在使用findOneAndUpdate来确保我不会两次添加相同的比赛(使用“ $ ne”)
Player.findOneAndUpdate({ '_id': player._id, 'tournamentSessions.tournament': { '$ne': tournament._id } }, { '$push': { 'tournamentSessions': { 'tournament': tournament._id, 'level': 1, 'status': 'LIMBO', 'score': 0, } } }, function(err, updatedPlayer) { // ... });
一切正常,除了包含ObjectID的“ _id”字段被添加到TournamentSessions数组内新添加的会话中之外,我无法理解为什么会这样。
如果我手动添加“ _id”字段并使用值“ BLABLABLA”,则永远不会存储“ _id”字段(因为它不应该,所以未在架构中声明)
是的,这是模式:
var Player = mongoose.model('Player', Schema({ createdAt: { type: Date, default: Date.now }, lastActiveAt: Date, clientVersion: String, tournamentSessions: [{ tournament: { type: Schema.Types.ObjectId, ref: 'Tournament' }, level: Number, status: String, score: Number }], friends: Array })); var Tournament = mongoose.model('Tournament', Schema({ createdAt: { type: Date, default: Date.now }, open: Boolean, number: Number, level: Number, reactionLimit: Number, deadlineAt: Date, stats: { total: Number, limbo: Number, blessed: Number, damned: Number } }));
您可以_id通过tournamentSessions使用自己的架构显式定义数组来禁用该字段,以便将其_id选项设置为false:
_id
tournamentSessions
false
var Player = mongoose.model('Player', Schema({ createdAt: { type: Date, default: Date.now }, lastActiveAt: Date, clientVersion: String, tournamentSessions: [new Schema({ tournament: { type: Schema.Types.ObjectId, ref: 'Tournament' }, level: Number, status: String, score: Number }, { _id: false })], friends: Array }));