plus-
plus-

Reputation: 46543

Mongoose _id affected before saving

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Cat = mongoose.model('Cat', { name: String });

var kitty = new Cat({ name: 'Zildjian' });
console.log(kitty);
kitty.save();
console.log(kitty);

this output:

{ name: 'Zildjian', _id: 523194d562b0455801000001 } twice

I've tried by delaying the save after a timeout, but it's the same, which points to the _id being set on the new Cat and not the .save()

Is this because of mongodb or mongoose, why is the _id set before the actual persistence?

Upvotes: 3

Views: 5534

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59763

Most MongoDb drivers will automatically generate the ObjectId/_id client side, including the native driver for Node.js. There's a tiny amount of locking that occurs to generate an ID uniquely, so there's little reason to not distribute the generation to connected clients.

Mongoose needs a unique identifier to track and reference objects, so it creates an identifier immediately.

In the Node.JS client you can optionally set for example the property forceServerObjectId to true to control this behavior.

However, this cannot be overridden when using Mongoose per the docs:

Mongoose forces the db option forceServerObjectId false and cannot be overridden. Mongoose defaults the server auto_reconnect options to true which can be overridden. See the node-mongodb-native driver instance for options that it understands.

Upvotes: 10

Related Questions