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.但是_id属性只有在进入db之后才会被添加到对象中.注意:我之前不想给它一个id.但是,我想抓取db中的对象,因为我需要使用_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...
})
edit:实际上 _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屋!