Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  15] [ 7]  / answers: 1 / hits: 29133  / 11 Years ago, tue, october 15, 2013, 12:00:00

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.


More From » node.js

 Answers
77

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.


[#74991] Sunday, October 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rossthomasn

Total Points: 122
Total Questions: 78
Total Answers: 105

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;