Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an _id with ObjectID added to when using MongoDB's $push to add new object to an array?

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
    }
}));
like image 857
bobmoff Avatar asked Dec 31 '13 21:12

bobmoff


People also ask

What is the use of ObjectId in MongoDB?

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.

What is an _id of type ObjectId?

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.

What is ObjectId in mongoose?

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.

Is MongoDB ObjectId increment?

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.


1 Answers

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
}));
like image 73
JohnnyHK Avatar answered Oct 24 '22 16:10

JohnnyHK