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

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

问题描述

有没有办法在 mongoose 中声明模型模式,以便在模型新建时 _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.

附言我正在使用猫鼬 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"});

但我宁愿不必导入 ObjectId 并且每次我想新建一个人时都必须新建它.我猜我习惯于使用 mongodb 的 java 驱动程序,我可以在模型构造函数中为 _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 以及 person 对象的其余部分

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天全站免登陆