-1

According to this, the params are:

  1. url (string) – connection url for MongoDB.
  2. [options] (object) – optional options for insert command
  3. callback (function) – this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.

But according to this, the first two params are the same, but the params passed to the callback function are different. The second param passed to the callback is a MongoClient instance.

Which one is correct? When I tested, the second source seems to be correct, but I wished the first was correct.

snehanshu.js
  • 137
  • 1
  • 12
  • 1
    The [documentation is quite clear](https://mongodb.github.io/node-mongodb-native/3.2/api/MongoClient.html#.connect). Not that `options` is marked as **optional**. Which basically means the function *optionally* accepts different parameters in addition to the **mandatory** `uri`. Additionally a `callback` is also *optional*, since invoking to return a `Promise` is also an "option". The only caveat is *at present* you will receive a warning if you omit the `useNewUrlParser` option, until the driver major version changes and the "new parser" is moved to the default. – Neil Lunn May 21 '19 at 10:56
  • I am not confused about `useNewUrlParser`, btw thanks for responding. – snehanshu.js May 22 '19 at 08:55
  • The point was not "just" that option, but the basic syntax of how to connect. Which you appear to be confused about since you asked the question. As stated, the documentation and the linked examples are very clear on the syntax. – Neil Lunn May 26 '19 at 02:09

2 Answers2

1

Both are correct, In older version 1.x or 2.x, callback(err, db)

while in newer version 3.x, callback(err, mongoClient)

If you are using newer version(not 1.x or 2.x) then use second one

Note: You may use https://mongodb.github.io/node-mongodb-native/ for specific version documentation

Arif Khan
  • 5,039
  • 2
  • 16
  • 27
0
Using below npm pack

 "mongodb": "^3.0.2",
 "mongoose": "^5.0.6"

Connect Mongo using Below Code
var db = {};
var mongoose = require('mongoose');
mongoose.connect(config.url);
//config.url is your Mongodb connection string
//Add your Model as required
db.Roles = mongoose.model("Roles",require("./schemas/roles.schema"));
//Export it to Module
module.exports = db;


You can call this common JS File

const db = require("../db");
const mongoose = require('mongoose');

//Sample Snippet change as Required

exports.getUserRoles = async (req) => {
    logger.info("Get User Roles service");
    const RoleModel = db.Roles;
    return await RoleModel.find({}, { "_id": 1, "name": 1, "features": 1 }).then(result => {
        return result
    }).catch(err => {
        throw err;
    });
};