MongoDB Atlas with NodeJS using Mongodb is not connecting - javascript

I'm getting an error when I'm trying to connect with MongoDB, error pointed toward connect while it's keyword itself. I didn't know what the issue here.
Error is :
mongodb.connect(
^
TypeError: mongodb.connect is not a function
let express= require('express')
let mongodb= require('mongodb').mongodb
let app = express()
let db
let connectionString = 'mongodb+srv://admin:admin#cluster0.sfis6s3.mongodb.net/ToDoApp?retryWrites=true&w=majority'
mongodb.connect(
connectionString,{useNewUrlParser: true}, function(err, client){
db = client.db()
})
app.use(express.urlencoded({extended:false}))

I think the reason is for that you must import MongoClient class
const MongoClient = require("mongodb").MongoClient;
reference:
connect is not a function when connecting to mongodb

Related

How does module.exports = mongoose; work when requiring "./database"?

I'm a MERN stack beginner. I came across this snippet of code from a basic CRUD and I know that it works, but I don't get how.
//in server.js
const database = require('./database');
//in database.js
const mongoose = require('mongoose'); //importing mongoose
mongoose.connect('mongodb://localhost/monguse', {useNewUrlParser:true}) //connected to db
.then((db)=>{console.log('Database connected')}) //message if ok
.catch((err) =>{console.log(`Database connection error: ${err}`)}); //catching errors
module.exports = mongoose;
I understand what is going on in database.js (It is my own version), but why does it work without using any method in server.js? It appears to make the connection only from using the "require" function. then in my routes there is no mention of that again; just using mongoose models in the requests.
Thanks!
In database.js you create an instance of the database and export it by name mongoose, and in server.js you are importing that instance of the mongoDB by name database.

MongoDB/Mongoose Connection Error when Dbname is used in the connection string

A NodeJS app uses mongoose 5.6.0 to connect to MongoDB 4.0.10 which runs on localhost inside a docker container.
The connection can be established when we use
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri)
Problem: We start getting authentication errors when we include the name of the database we are connecting to. There is no problem using Python to connect to the same MongoDB database.
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri)
and also tried
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri, { useNewUrlParser: true })
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Authentication failed.
Why is it unable to make the connection and how can we solve this problem?
Update
Found the solution to be
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri, { useNewUrlParser: true, dbName: 'my-db' })
Why must the dbname be passed as an option instead of including it in the connection string?
This has worked for me, thanks.
var result = await mongoose.connect('mongodb://root:example#localhost:27017/', {useNewUrlParser: true,dbName: 'my-db'})
Short answer: Add ?authSource=admin to URI string or use {authSource:"admin"}
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db?authSource=admin'
mongoose.connect(mongoUri)
Follow this answer https://stackoverflow.com/a/68137961/12280326 for detailed explanation.

How should in right way connecting MongoDB in Nodejs?

Hello i am new in Nodejs & MongoDb.
I created controllers for API where i want create new items in MongoDB, edit, search items.
Now i am connecting to MongoDB via mongoose in main file server.js.
But i need that i can create, edit in editor.js.
I tried to export mongoose module, but it was unsuccessfull.
How i can do this in right way?
my structure
`editor.js` file - where i want have access to database
const models = require('./../models');
const client = require('./../../server');
const mongoose = require('mongoose');
let db;
// const db = client.db('todo');
module.exports = {
getNewsById: async (req, res) => {
console.log(req.params);
// console.log(req);
res.send({oK: 'ok'});
},
createNews: async (req, res) => {
const newItem = req.body;
newItem['publishedAt'] = Date.now();
console.log('HERE', client);
console.log('HERE2', client.db.collection('test').insertOne({
item: 'canvas',
qty: 100,
tags: ['cotton'],
size: { h: 28, w: 35.5, uom: 'cm' }
}));
}
}
In editor.js after importing mongoose, you can simply load your model using -
const db = require('mongoose');
const testModel = db.model('test');
And then you can call your db queries similar to -
testModel.insert(...);
testModel.find();
Once you have built your model using mongoose, it is available in the application. You just need to get it through mongoose.
If you need more help, you can refer to my sample project at https://github.com/kravigupta/nodejs-express-mongo-auth
For every new developer who is learning node.js, the first thing they go with the MongoDB connection with the node.js.
I will suggest you keep the MongoDB connection URL, username and password in a separate file say it db.config.js file and then import that file into you server.js or app.js or main file of your node.js and then connect mongo with the try catch block to handle the error. IF you need to learn in more details then you can refer to this link.

Why is Nodemon server crashing when trying to start Mongo server?

I am new to creating nodejs application. I am trying to get started with simple angular, and nodejs application. I have saved my data in "mLab". Now when I am trying to display my data through this below code, my nodemon server is crashing describing,
"MongoError: failed to connect to server [ds030817.mlab.com:30817]".
Here is my code I have copied from other source.
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://<dbuser>
<dbpassword>#ds030817.mlab.com:30817/user_data_0001',['books']);
router.get('/tasks', function(req, res, next){
db.books.find(function(err, books){
if(err){
res.send(err);
}
res.json(books);
})
});
module.exports = router;
Your connection string format is not right. Use following
var db = mongojs('mongodb://dbuser:dbpassword#ds030817.mlab.com:30817/user_data_0001',['books']);

Share database connection among multiple routes? [duplicate]

This question already has answers here:
Best way to share database connection param with mongoose/node.js
(3 answers)
Closed 8 years ago.
I've created an extremely simple Node.js app based on Express's route-separation example. I want to power this app with the MongoDB driver Mongoose. This example just lists Users and Kittens.
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var user = require('./user');
var kitten = require('./kitten');
// Connect MongoDB
mongoose.connect('mongodb://localhost/mongoose');
// Express config here
...
// User
app.all('/users', user.list);
// Kitten
app.all('/kittens', kitten.list);
// Mongoose connection
var db = mongoose.connection;
db.once('open', function callback () {
var kittySchema = mongoose.Schema({ name: String });
});
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
To me it seems it would be wise to connect to the Mongo database on startup rather than for each request.
But how do I share that Mongoose connection with both the user and kitten routes? I know if I didn't need to share the connection between the two, I could just connect to the database in my user.js and kitten.js code.
In node.js when you do require a file, you run the code in that file exactly once. Which means you can store things through closure.
foobardb.js
(function(){
"use strict"; // always nice to have
var mongoose = require('mongoose'),
databaseConnection;
module.exports = function() {
if ( !databaseConnection ) {
mongoose.connect('mongodb://localhost/mongoose')
databaseConnection = mongoose.connection;
}
(...)
};
})();
The databaseConnection will be shared with all the require("foobardb.js"); you do

Categories