Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

New to Node, Mongoose & Mongodb - haven't read the source code...

I have a Node application which opens a file, parses the lines into records and saves the records to mongodb. The records are Mongoose model objects, and to save them to mongodb all I do is invoke the save method on them.

So now I'm all worried about the connection that mongoose is managing db = mongoose.connect(url). Do I need to manually close it? If so, when should I close it (since everything is happening async it is hard to say when to close the connection)?

It seems that mongoose doesn't only keep the connection open, but also it keeps my script from terminating. Can I safely close the mongoose connection after I've called save on all my objects? Otherwise given the async nature of the save, it would be difficult to know exactly when shutdown the connection.

See Question&Answers more detail:os

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

1 Answer

You do need to call mongoose.disconnect() to close the connection, but you also need to wait until all save calls have completed their async work (i.e. called their callback) before doing that.

So either keep a simple count of how many are still outstanding to keep track or use a flow control framework like async to do something a bit more elegant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...