I'm new to Node.js and MongoDB. I installed all packages as specified in a YouTube tutorial. I tried a lot to connect MongoDB with Node.js, but there is no error messages and it is not connected. I have downloaded Mongo Shell as well. Everything works perfectly, the connection message is not displayed. It works on my command prompt, but not in vs code. I'm creating a sample project with Express generator. What's wrong with my code?
Here is my code:
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/signup', function(req, res) {
console.log(req.body);
MongoClient.connect('mongodb://localhost:27017', function(err, client){
if(err)
console.log('error')
else
console.log('mongodb connected...')
})
res.send('Got it.')
})
Try my simple code below, if it works, it says "Connected successfully to server" in the console log. It is only the first step.
//const { MongoClient } = require('mongodb');
// or as an es module:
import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
Try to install the mongodb driver again using this file package.json content:
{
"name": "mongodb",
"version": "1.0.0",
"description": "",
"main": "mongodbsort.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"mongodb": "^4.17.2"
}
}
the row "type": "module", is important