node.js - How to operate Mongodb in node project? Is my approach feasible?
女神的闺蜜爱上我
女神的闺蜜爱上我 2017-06-10 09:48:03
0
1
678

The first time I came into contact with the node project, I used the node-mongodb-native module officially provided by mongodb to connect and operate mongodb.

I connected the database in the entrance app.js, but I want to operate the database elsewhere. Here is what I do:

var MongoClient = require('mongodb').MongoClient()

MongoClient.connect(url, function(err, db) {
    global.db = db
})

I mounted the db parameters under global so that the database can be operated anywhere else:

global.db.collection('documents')

I feel like there will be problems with this, but I can’t tell where the problem is. Please give me some advice.

女神的闺蜜爱上我
女神的闺蜜爱上我

reply all(1)
某草草

Usually the database connection is done in app.js/server.js, and the database operation part is:

1. You can write it directly in app.js/server.js;

2. You can also save it separately in other files, just require it in app.js/server.js;

For example, the code for collection operation of user is placed in user.js, module.exports in user.js; and then required in app.js/server.js.

It’s just a form of code organization. You can choose according to your own situation.

So it is recommended that you consider the above approach.

For reference.

Love MongoDB! Have fun!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template