How to connect a mongo db to node.js - node.js

I was following a tutorial and there the mongo db is connected in this way:
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
let _db;
const mongoConnect = (callback) => {
MongoClient.connect(
"mongodb+srv://Narayan:UQWrtyZcNfYmzYrd#cluster0.nh7pm.mongodb.net/?retryWrites=true&w=majority"
)
.then((client) => {
console.log("Connected to MongoDB");
_db = client.db();
callback(client);
})
.catch((err) => {
console.log(err);
throw err;
});
};
const getDb = () => {
if (_db) {
return _db;
}
throw "No database found!";
};
exports.mongoConnect = mongoConnect;
exports.getDb = getDb;
and the app just didn't work . Is this a correct way of connecting a node.js to a mongodb?

Related

MongoDB won't insert document

I don't know what I am doing wrong, however the following is not working.
I have the database connecting however when I try and use the connection it won't let me.
index.js
config = require('./config');
const express = require('express');
const app = express();
const mDB = require('./components/mongodb').connect(config.dbUri);
app.get('/testDB', (req,res) =>{
const user = { name: 'John', age: 30 };
mDB.insertOne(user, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted user: ${result.insertedId}`);
res.send("inserted");
});
});
app.listen(3000, () => {
console.log('App listening on port 3000');
});
./components/mongodb.js
const MongoClient = require('mongodb').MongoClient;
module.exports.connect = (uri) => {
MongoClient.connect(uri, { useNewUrlParser: true }, (err, client) => {
if (err) {
console.error(`MongoDB connection error: ${err}`);
process.exit(1);
}
console.log('Successfully connected to MongoDB');
module.exports.client = client;
});
};
module.exports.insertOne = (collection, document) => {
module.exports.client.db('PodToo').collection(collection).insertOne(document, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted document: ${result.insertedId}`);
});
};
I get the Successfully connected to MongoDB
But then when I try and use it I am receiving
TypeError: Cannot read properties of undefined (reading 'insertOne')
In the danger of stating the obvious: You are missing the first argument to your insertOne function, the collection name.
Did you mean
mDB.insertOne('users', user, ...
?

db.collection is not a function when nodejs connect to mongodb via MongoDB native NodeJS driver

I'm trying to connect to mongoDB via mongodb native nodejs driver, but I'm having a problem.
conn.js
'use strict'
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017/test';
const dbname = 'test';
const dbConnect = () => {
return new Promise((resolve, reject) => {
MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
if (err) {
reject(err);
} else {
resolve(client.db(dbname));
}
});
});
}
module.exports = {
dbConnect
}
user.js
const conn = require('../conn');
router
.post('/', async (ctx, next) => {
try {
let user = await conn.dbConnect.collection('user').findOne({email: email});
console(user);
} catch (e) {
ctx.body = {error:true, msg: e instanceof Error ? e.message : e};
}
})
module.exports = router;
But I got the error db.collection is not a function, why? Thank you.

Can .save() Mongoose Schema only one time, next i need to restart node.js server to save it again

i have this problem. First i start Mongoose connecting it to Atlas Db.
dbConfig.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://myMongoDbOnAtlas?retryWrites=true&w=majority";',
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
);
mongoose.connection.once('open', () => {
console.log('Connected to db');
}).on('error', (error) => {
console.warn('Error: ' + error);
})
module.exports = mongoose;
/db/schema/offices.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const OfficeSchema = new Schema({
// Some Properties
});
const Office = mongoose.model('offices', OfficeSchema);
module.exports = Office;
addOfficeController.js
const Office = require('../db/schema/office');
const mongoose = require('../db/dbConfig');
const addOffice = async (req, res, next) => {
const office = req.body;
let newOffice = new Office(office);
newOffice.save((err, data) => {
if(err){
res.status(400).send(err);
console.log(err);
}else{
res.status(201).send(data);
}
mongoose.connection.close();
})
};
module.exports = {
addOffice
};
Now when i start the Node server my controller works fine and save on db the data, but if i try to do it again the callback is an error: MongooseError: Operation offices.insertOne() buffering timed out after 10000ms
Ok i solved in this way
const mongoose = require('mongoose');
const startDb = () => {
mongoose.connect('myMongoDb#cluster0.hazp8.mongodb.net/db?retryWrites=true";',
{
useUnifiedTopology: true,
useNewUrlParser: true,
}
);
mongoose.connection.once('open', () => {
console.log('Connected to db');
}).on('error', (error) => {
console.warn('Error: ' + error);
})
}
module.exports = startDb;
I exported a function that starts the connection to db, and after save() I close the connection.

Problems returning database information with MongoDB, Node.js and Express

const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myorders';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("The connection was awesome");
const db = client.db(dbName);
second.get('/Students',(req,res) => {
const findStudents = function(db,call) {
const collection = db.collection('Students');
collection.find({}).toArray(function (err,result) {
if (!err) {
res.send(result)
} else {
console.log(err);
call(err);
}
});
}
});
client.close();
});
second.listen(3200,() => {
console.log('We got it running');
});
module.exports = second;
So I am trying to display my mongodb information on a web server and here are the screen shots
Above is the MongoDB collection of students and marks
And above is my Node.js command prompt and I get a deprecation warning. Is there any way I can fix it? Is there any other error why I can't display the information in the web server?
To fix this deprecation warning, all you need is to do what it says: pass the option useNewUrlParse: true in the options object to MongoClient.connect. So the line where you connect to MongoDB database would be:
MongoClient.connect(url, { useNewUrlParse: true }, function(err, client)
Anyway, this is just a warning, not a blocking error, and your app is running. I think there are several things wrong in your code, mainly that you declare the function to be executed on the GET to /Students within the callback of the connection to the database and that you close that connection so that the data could no longer be accessed. I think this code should work for you:
const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbUrl = 'mongodb://localhost:27017';
const dbName = 'myorders';
let db;
MongoClient.connect(url, (err, client) => {
assert.equal(null, err);
db = client.db(dbName);
console.log("The connection was awesome");
});
second.listen(3200, () => {
console.log('We got it running');
});
second.get('/Students', (req, res) => {
db.collection('Students').find().toArray((err,result) => {
if (!err) {
res.send(result)
} else {
console.log(err);
res.status(500).send(err);
}
});
});
EDIT:
If you think that the database should not be always opened, yous should connect and close at each request to /Students, this way:
second.listen(3200, () => {
console.log('We got it running');
});
second.get('/Students', (req, res) => {
MongoClient.connect(url, (err, client) => {
if (err) return res.status(500).send(err);
db = client.db(dbName);
db.collection('Students').find().toArray((err,result) => {
if (!err) {
res.send(result)
} else {
console.log(err);
res.status(500).send(err);
}
client.close();
});
});
});

Heroku Error: Invalid schema, expected `mongodb` or `mongodb+srv`

My app is able to connect to MongoDB locally but on heroku logs i'm getting this error:
Error: Invalid schema, expected mongodb or mongodb+srv
This is what my connection to mongodb looks like in my server.js file:
// // DB config
const db = require("./config/keys").mongoURI;
// // Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
config/keys:
if (process.env.NODE_ENV === "production") {
module.exports = require("./keys_prod");
} else {
module.exports = require("./keys_dev");
}
keys_dev:
module.exports = {
mongoURI:
"mongodb://jenn123:jenn123#devconnect-shard-00-00-acrk4.mongodb.net:27017,devconnect-shard-00-01-acrk4.mongodb.net:27017,devconnect-shard-00-02-acrk4.mongodb.net:27017/test?ssl=true&replicaSet=devconnect-shard-0&authSource=admin&retryWrites=true",
secretOrKey: "secret"
};
keys_prod:
module.exports = {
mongoURI: "process.env.MONGO_URI",
secretOrKey: "process.env.SECRET_OR_KEY"
};
Any help is greatly appreciated
Well, you're doing the production keys wrong.
process.env is an object containing the env variables as key and their values.
so instead of putting them in a string, you gotta remove the string and treat it as an object. like below:
module.exports = {
mongoURI: process.env.MONGO_URI,
secretOrKey: process.env.SECRET_OR_KEY
};
This is typically how I connect with mongoose.
const mongoose = require('mongoose');
const dotenv = require('dotenv').config();
let db = mongoose.connection;
mongoose.connect('your connection URL here', {
auth: {
user: "Your username",
password: "Your password"
}
})
.then(() => {
console.log('connection successful')
db = mongoose.connection;
module.exports = db;
})
.catch((err) => {
console.error(err)
});
You can then use it in a file like so (this is assuming you've defined a job schema and are importing it):
const db = require('./db'); // provides the mongoDB connection
const mongoose = require('mongoose');
const ObjectId = require('mongoose').Types.ObjectId;
const Job = require('./schemas/jobs').Job
module.exports.createJob = function (newJob) {
const job = new Job(newJob);
return new Promise((resolve, reject) => {
job.save((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};

Resources