Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

javascript - Mongoose with mongodb how to return just saved object?

I'm new to mongoose/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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The _id should be present after saving:

var instance = new TestingModel()

instance.test = 'blah'

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

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...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...