猫鼬模型被新建时,有没有一种方法可以自动生成ObjectId? [英] is there a way to auto generate ObjectId when a mongoose Model is new'ed?

查看:93
本文介绍了猫鼬模型被新建时,有没有一种方法可以自动生成ObjectId?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以用猫鼬声明模型架构,以便在模型更新后自动生成_id字段?

is there a way to declare a Model schema in mongoose so that when the model is new'ed the _id field would auto-generate?

例如:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectIdSchema = Schema.ObjectId;
var ObjectId = mongoose.Types.ObjectId;

var PersonSchema = new Schema({
    _id:            ObjectIdSchema,
    firstName:      {type: String, default: 'N/A'},
    lastName:       {type: String, default: 'N/A'},
    age:            {type: Number, min: 1}
});

var Person = mongoose.model('Person', PersonSchema);

起初,我认为太好了!,我会做

at first, i thought great!, i'll just do

_id:    {type:ObjectIdSchema, default: new ObjectId()}

但是当然不行,因为new ObjectId()仅在模式初始化时调用.因此,两次调用new Persion()会创建两个具有相同_id值的对象.

but of course that doesn't work, because new ObjectId() is only called on initialize of schema. so calling new Persion() twice creates two objects with the same _id value.

有没有办法做到这一点,以便每次我执行"new Person()"时都会生成一个新的ObjectId()?

so is there a way to do it so that every time i do "new Person()" that a new ObjectId() is generated?

我尝试执行此操作的原因是因为我需要知道新人员的_id值的值以进行进一步处理.

the reason why i'm trying to do this is because i need to know the value of the new person's _id value for further processing.

我也尝试过:

var person = new Person({firstName: "Joe", lastName: "Baz"});
person.save(function(err, doc, num){
    console.log(doc._id);
});

即使这样,doc也不会包含ObjectId.但是如果我查看数据库,它确实包含它.

even then, doc doesn't contain the ObjectId. but if i look in the database, it does contain it.

p.s.我正在使用猫鼬2.7.1

p.s. i'm using mongoose 2.7.1

p.p.s.我知道我可以像这样创建人时手动创建ObjectId:

p.p.s. i know i can manually create the ObjectId when creating the person as such:

var person = new Person({_id: new ObjectId(), firstName: "Joe", lastName: "Baz"});

但是我宁愿不必每次导入新的Person时都必须导入ObjectId并更新它.猜猜我已经习惯了将Java驱动程序用于mongodb,在这里我可以在Model构造函数中为_id字段创建值.

but i rather not have to import ObjectId and have to new it every time i want to new a Person. guess i'm used to using the java driver for mongodb, where i can just create the value for the _id field in the Model constructor.

推荐答案

调用var person = new Person()的那一刻; person._id应该给您id(即使尚未保存).只需实例化它就可以给它一个id.之后,您仍然可以保存它,它将存储ID以及其他人员对象

the moment you call var person = new Person(); person._id should give you the id (even if it hasn't been saved yet). Just instantiating it is enough to give it an id. You can still save it after, and that will store the id as well as the rest of the person object

这篇关于猫鼬模型被新建时,有没有一种方法可以自动生成ObjectId?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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