search

Home  >  Q&A  >  body text

node.js - How to operate Mongodb in node project? Is my approach feasible?

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.

女神的闺蜜爱上我女神的闺蜜爱上我2715 days ago670

reply all(1)I'll reply

  • 某草草

    某草草2017-06-10 09:50:03

    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!

    reply
    0
  • Cancelreply