Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
plus- Avatar asked Mar 03 '26 03:03

plus-


1 Answers

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.

like image 189
WiredPrairie Avatar answered Mar 05 '26 19:03

WiredPrairie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!