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
290 views
in Technique[技术] by (71.8m points)

javascript - Do I need to manually close a mongoose connection?

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

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

1 Reply

0 votes
by (71.8m points)

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.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...