How to use mongoDB with node - node.js

When I run the script, the error returns.
TypeError: db.collection is not a function
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://abc:12345**#xxxx.mlab.com:&&&&/myDB";
MongoClient.connect(url, function(err, db) {
if(err) {
console.log(err);
} else {
console.log("Database created!");
db.collection('users').aggregate([{
'$match': {
'organization.organizationId': "e1716c62-fdce-11e7-8be5-
0ed5f89f718b"
}
},{
"$project": {
"deviceDetails": 1,
"userDetails": 1
}
}], function(error, documents) {
if (error) {
console(error);
} else {
console.log(documents);
}
});
});
Hi, could you please help me where am I doing wrong.Thanks!

With Mongo Driver 3.0 or above, the connect callback returns err and client instead of db. To get the db out of the client do this,
var db = client.db;
In your case, it will look something like this,
MongoClient.connect(url, function(err, client) {
if(err) {
console.log(err);
} else {
var db = client.db;
console.log("Database created!");
db.collection('users').aggregate(...)
}
})

Use MongoClient.connect(url, function(err, client)) where this was released in recent updates. For more info refer Mongo Driver Docs.
var MongoClient = require('mongodb').MongoClient;
// Dont use database name in link
var url = "mongodb://abc:12345**#xxxx.mlab.com:&&&&";
MongoClient.connect(url, function(err, client) {
if (err) {
console.log(err);
} else {
let db = client.db('myDB')
console.log("Database created!");
db.collection('users').aggregate([{
'$match': {
'organization.organizationId': "e1716c62-fdce-11e7-8be5-0e d5f89f718b "
}
}, {
"$project": {
"deviceDetails": 1,
"userDetails": 1
}
}], function(error, documents) {
if (error) {
console(error);
} else {
console.log(documents);
}
});
}
});

First you should check that database connect or not only run this code so that this confirm that variable url is correct or mongodb is correctly installed.
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log("Failed connecting to the database. " + err);
}
else
{
console.log(Sucessfully)
}
});

Related

Mongodb find not printing json data

In the code I am trying to find all documents with code UE19CS204.But in the console.log
a big message is printed not the JSON data.The findOne() is working but not find().
I don’t know what change to do to find all documents with code UE19CS204.
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);
dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here.
Use toArray(), you can finde the documentation here.
dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
Full example:
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) {
throw err;
}
client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
client.close();
});

Mongodb.connect does not execute callback function

Im trying to connect to my Mongodb and insert some documents if they are not already in the db. It works fine with the first inserts but in the function existInDatabase it sometimes does not execute the callback function.
var MongoClient = require('mongodb').MongoClient;
var mongoData = require('./mongoData');
var exports = module.exports = {};
var dbName = 'checklist';
MongoClient.connect(mongoData.ConString, {
useNewUrlParser: true
}, function(err, db) {
if (err) throw err;
for (var key in mongoData.Customers) {
if (!existsInDatabase(mongoData.Customers[key], 'Customers')) {
db.db(dbName).collection('Customers').insertOne(mongoData.Customers[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
db.close();
});
}
}
for (var key in mongoData.Categorys) {
if (!existsInDatabase(mongoData.Customers[key], 'Customers')) {
db.db(dbName).collection('Categorys').insertOne(mongoData.Categorys[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
db.close();
});
}
}
});
function existsInDatabase(obj, collection) {
var result = false;
MongoClient.connect(mongoData.ConString, {
useNewUrlParser: true
}, function(err, db) {
db.db(dbName).collection(collection).find({}).forEach(function(doc) {
if (doc.id == obj.id) {
result = true;
}
}, function(err) {
console.log(err);
});
});
return result;
}
I have made a few changes to your code. It seems you are new to async programming, spend some time to understand the flow. Feel free for any further query. Here is your code.
// Welcome to aync programming
// Here no one waits for the slow processes
var MongoClient = require('mongodb').MongoClient;
var mongoData = require('./mongoData');
var exports = module.exports = {};
var dbName = 'checklist';
// Make the connection for once only
MongoClient.connect(mongoData.ConString, { useNewUrlParser: true },
function(err, db) {
if (err) throw err;
var myDB = db.db(dbName); // create DB for once
for (var key in mongoData.Customers) {
//make call to the function and wait for the response
existsInDatabase(mongoData.Customers[key], 'Customers', function(err, result) {
//once the response came excute the next step
if (result) {
myDB.collection('Customers').insertOne(mongoData.Customers[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
});
}
});
}
for (var key in mongoData.Categorys) {
//make call to the function and wait for the response
existsInDatabase(mongoData.Customers[key], 'Customers', function(err, result) {
//once the response came excute the next step
if (result) {
myDB.collection('Categorys').insertOne(mongoData.Categorys[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
});
}
});
}
// Both the for loop will work randomly without any order
function existsInDatabase(obj, collection, cb) {
var result = false;
myDB.collection(collection).findOne({ id: obj.id }, function(err, result)
{
if (err) {
//this cb will work only when db operation is complited
cb(err);
} else if (result) {
cb(null, true);
} else {
cb(null, false);
}
});
}
});
This code may result in some error. Feel free to ask more questions over it
db.db(dbName).collection(collection).find({}) returns a cursor per the docs. You are missing .toArray():
db.db(dbName).collection(collection).find({}).toArray()...

Finish execution if first query returns a value Node.js Express.js mongoDB

Before starting, please mind that i have been searching this over 2+ hours, the answer will be simple i know but i couldnt get it to work . i am new to express node mongodb,
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("EXISTS");
//I WOULD LIKE TO EXIT IF THIS LINE EXECUTES
}
}
});
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("CREATED 201");
} else {
res.send("Failed to insert");
}
}
});
db.close();
});
my goal is to check if an user doesnt exists with given username, i would like to insert that to the DB.
i would like to exit if my query finds an match and arrange such that insertOne wont execute. please enlighten me!!
Once you are not using the async/await syntax you will have to nest the calls to MongoDB, so they execute in series. You can also use a module like async to achieve this.
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
if (result) {
db.close();
return res.send("EXISTS");
}
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
db.close();
if (result) {
return res.send("CREATED 201");
}
res.send("Failed to insert");
});
});
});
Try this
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
//put the error logic
}
else {
if (result) {
//Send the response
return result;
}
else{
// if above if block fails it means that user does not exist
//put the insert logic
}
});

How can I store the result of MongoDB query in a text file with Nodejs?

I get and store the data from mongoDB into txt file by using the following code.
But when I open txt file. Nothing is saved.
var express = require('express');
var router = express.Router();
var fs = require('fs');
var mongodb = require('mongodb').MongoClient;
mongodb.connect('mongodb://127.0.0.1:27017/data', function(err, db) {
if (err) throw err;
var test = db.collection('test');
for (var i = 0; i < 10; i++)
{
test.find({ "number": i }, {"email": 1, "_id": 0}).toArray(function (err,data) {
if (err) throw err;
fs.writeFile("/tmp/test", data, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
//console.log(data);
});
}
});
It's result of console.log(data);
[ { email: 'example#email.com' } ]
[ { email: 'test#email.com' } ]
[]
[ { email: 'email#email.com' } ]
.......
How can store result of MongoDB query in text file ?
mongodb.connect('mongodb://127.0.0.1:27017/data', function (err, db) {
if (err) throw err;
var test = db.collection('test');
recursiveadd(0,10,"",function(err,data){
if (err) {
return console.log(err);
}else{
fs.writeFile("/tmp/test", data, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
})
});
function recursiveadd(i,n,datatofile,cb){
if(i>n){
cb(undefined,"success");
return;
}
test.find({
"number": i
}, {
"email": 1,
"_id": 0
}).toArray(function (err, data) {
if (err)cb(err);
datatofile = datatofile + " " + JSON.stringify(data);
});
recursiveadd(i++,n,datatofile,cb);
}
The reason your getting undefined is because fs.WriteFile() is being called before the data has finished loading. You need to use promises and do something like this:
mongodb.connect('mongodb://127.0.0.1:27017/data', function (err, db) {
if (err) throw err;
var test = db.collection('test');
var datatofile;
function process(){
return new Promise((resolve,reject) => {
for (var i = 0; i < 10; i++) {
test.find({
"number": i
}, {
"email": 1,
"_id": 0
}).toArray(function (err, data) {
if (err) throw err;
datatofile = datatofile + " " + JSON.stringify(data);
});
resolve(datatofile);
}
process()
.then(function(data){
fs.writeFile("/tmp/test", data, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
Please note haven't run this so may not work, however you need to use promises as the asynchronous aspect is causing the undefined error.

How to use findOneAndUpdate in MongoDB in Node

Say previously I had inserted a document into a mongo collection.
MongoClient.connect(url, function(err,db){
if(err) {throw err;}
else {
document = {action: "alert",
protocol: "udp",
port: "80",
_id: "12" }
var collection = db.collection("connections");
collection.insertOne(document, function(err,result){
if (err) {throw err;}
else {
console.log("Successful")
db.close();
}
}
}
Now I want to update the protocol field. What I have with no luck so far is
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {new: true}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
Am I passing the wrong parameters to the findOneAndUpdate method? I connect to the database correctly.
I think you should try
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {upsert: true}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
If "upsert" set to true, creates a new document when no document matches the query criteria.
=== Aug 2021
Here is an example of using findOneAndUpdate and getting back the updated document:
With the release of v4 of the node.js client, it seems the old solution of returnOriginal: false (which was awful anyway) is no longer the correct answer.
To see the list of available options for the node.js findOneAndUpdate method: https://mongodb.github.io/node-mongodb-native/4.0/interfaces/findoneandupdateoptions.html
But in short, this should work:
const doc = await <Collection>.findOneAndUpdate(
{ ... search },
{
$set: {
field1: 'value 1',
field2: ['value 2'],
etc.
},
},
{
upsert: true,
returnDocument: 'after', // this is new !
}
)
your third {new: true} argument is not valid
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({"_id": "12"}, {$set: {"protocol": "http"}}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
Here to update the record,it is not needed to use {upsert: true} and {new: true}. This solution works better.Try it once and suggest me if any errors in the code.
insert the update document if nothing matches the filter then use upsert.
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({_id: "12"}, {protocol: "http"}, {new: true}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});

Resources