Javascript Mongoose with mongodb 如何返回刚刚保存的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7479333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:26:40  来源:igfitidea点击:

Mongoose with mongodb how to return just saved object?

javascriptmongodbmongoose

提问by Derek

I'm new to mongoose/mongodb

我是猫鼬/mongodb 的新手

Say I'm saving something:

说我正在保存一些东西:

var instance = new TestingModel();
instance.test = 'blah2';
instance.save();

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?

因此,当我保存数据库中的实例 obj 时, _id 和 test. 但是_id属性只有在进入db之后才会被添加到对象中。注意:我之前不想给它一个id。但是,我想抓取db中的对象,因为我需要使用_id值,但我不想再次查询它。有没有办法将对象保存在数据库中并自动返回数据库对象,以便获得 _id 值?

回答by Ricardo Tomasi

The _idshould be present after saving:

_id应在保存后存在:

var instance = new TestingModel()

instance.test = 'blah'

instance.save(function(err){
    console.log(instance._id) // => 4e7819d26f29f407b0...
})

edit: actually the _idis set on instantiation, so it should already be there before save:

编辑:实际上_id是在实例化时设置的,因此在保存之前它应该已经存在:

var instance = new TestingModel()
console.log(instance._id) // => 4e7819d26f29f407b0...

回答by sh977218

The correct way to check is the callback of save :

正确的检查方法是 save 的回调:

instance.save(function(err,savedObj){
    // some error occurs during save
    if(err) throw err;
    // for some reason no saved obj return
    else if(!savedObj) throw new Error("no object found") 
    else console.log(savedObj);
})

回答by user3444748

router.post('/', function(req, res) {
    var user = new User();
    user.name = req.body.name;
    user.token = req.body.token;

    user.save(function(err, obj) {
        if (err)
            res.send(err);

        res.json({ message: 'User created!', data: obj });
    });
});