Mongoose与mongodb如何返回刚刚保存的对象? [英] Mongoose with mongodb how to return just saved object?
问题描述
我是mongoose / mongodb的新手
I'm new to mongoose/mongodb
说我保存了一些东西:
var instance = new TestingModel();
instance.test = 'blah2';
instance.save();
因此,当我保存数据库中的实例obj将具有,_id和test时。但只有在进入db后才会将_id属性添加到对象中。注意:我之前不想给它一个id。但是,我想抓住数据库中的对象,因为我需要使用_id值,但我不想再次查询它。有没有办法将对象保存在数据库中并自动返回数据库对象以便获取_id值?
So when I save that the instance obj in the db will have, _id and test. But the _id attribute is added to the object only after entering the db. Note: I don't want to give it an id before. However, I want to grab the object in the db because I need to use the _id value, but I don't want to query it again. Is there a way where you save the object in the database and auto returns the database object so you can get the _id value?
推荐答案
保存后应存在 _id
:
var instance = new TestingModel()
instance.test = 'blah'
instance.save(function(err){
console.log(instance._id) // => 4e7819d26f29f407b0...
})
编辑:实际上 _id
是在实例化时设置的,所以在保存之前它应该已存在:
edit: actually the _id
is set on instantiation, so it should already be there before save:
var instance = new TestingModel()
console.log(instance._id) // => 4e7819d26f29f407b0...
这篇关于Mongoose与mongodb如何返回刚刚保存的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!