简体   繁体   中英

issue while connecting mongoDB with node.js

I am trying to connect mongodb and node.js for a project I'm working on.

I have set up a database as follows: click here to view the status of the database

and I have a file called index.js in D:\\node.JS. Here's the content of the file:

const MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/test";

MongoClient.connect(url, function(err, db){
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

And this is the output I'm getting:

D:\node.JS>node index.js
D:\node.JS\index.js:6
mongoClient.connect(url,(err,databse)
                                    ^

SyntaxError: missing ) after argument list
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

Where can I have gone wrong?

This is the actual way to connect to MongoDB using Mongoclient function

  const MongoClient = require('mongodb').MongoClient;
  const test = require('assert');
 * // Connection url
  const url = 'mongodb://localhost:27017';
 * // Database Name
  const dbName = 'test';
 * // Connect using MongoClient
  MongoClient.connect(url, function(err, client) {
  const db = client.db(dbName);
    client.close();
  });

for more reference see this https://github.com/mongodb/node-mongodb-native/blob/3.0.0/lib/mongo_client.js#L39

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

var db;

// Initialize connection once

MongoClient.connect("mongodb://localhost:27017/test", function(err, database) {

if(err) return console.error(err);

db = database;

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM