I am using Node.js and Mongoose. player and tournament variables are Mongoose objects, fetched just before.
I want to add a new tournamentSession object (NOT a Mongoose object) into the tournamentSessions field of the player object. I am using the findOneAndUpdate to be able to make sure that I dont add the same tournement twice (using the "$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) {
// ...
});
Everything works fine, except that the "_id" field containing an ObjectID is added to the newly added session inside the tournamentSessions array, and I cant understand why this is happening.
If I manually add the "_id" field and with the value "BLABLABLA", the "_id" field is never stored (as it shouldnt, coz its not declared in the schema)
Ye, And here is the schemas:
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
}
}));
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.
Architecturally, by default the _id field is an ObjectID, one of MongoDB's BSON types. The ObjectID is the primary key for the stored document and is automatically generated when creating a new document in a collection.
ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents.
You can disable the _id
field by explicitly defining the tournamentSessions
array with its own schema so that you can set its _id
option to 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
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With