猫鼬_id在保存前受影响 [英] Mongoose _id affected before saving

查看:55
本文介绍了猫鼬_id在保存前受影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

此输出:

{ name: 'Zildjian', _id: 523194d562b0455801000001 }两次

我尝试过在超时后延迟保存,但这是相同的,它指向在new Cat而不是.save()

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()

这是因为mongodb还是mongoose,为什么在实际持久性之前设置_id?

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

推荐答案

大多数MongoDb驱动程序将自动生成ObjectId/_id客户端,包括Node.js的本机驱动程序.唯一的生成ID的锁很小,因此没有理由不将生成分发给连接的客户端.

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.

在Node.JS客户端中,您可以可选设置例如属性forceServerObjectIdtrue来控制此行为.

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

但是,根据 docs :

猫鼬强制db选项forceServerObjectId为false,并且不能为 覆盖.猫鼬默认将服务器的auto_reconnect选项设置为 可以覆盖的true.请参阅node-mongodb-native驱动程序 它了解的选项的实例.

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.

这篇关于猫鼬_id在保存前受影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆