Find result based on id in mongo db using node.js - node.js

I want to find result from collection using node.js in mongodb. My code is as follows
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
collection.findOne({_id:req.body.Id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
I am not able to get required result.Getting error collection is not defined.

Try convert id to ObjectId:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
db.collection('collectionName').findOne({_id:new ObjectID(req.body.Id)},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});

You need to define which collection you're going to query:
db.collection('CollectionName').findOne({_id: req.body.Id}, function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
db.close();
});
Node.js MongoDB Driver API - findOne

Related

How to solve insertOne is not a function problem

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';
MongoClient.connect(url, {useNewUrlParser: true}, function(err, db){
if(err) throw err;
var dbo = db.db('mydb');
var myObj = [{name: 'Company Inc', address: 'Highway 37'}];
dbo.createCollection('Customers').insertone(myObj, function(err, res){
if(err) throw err;
console.log('1 document inserted!');
db.close();
});
});
My code is not working, the error is insertOne is not a function. My mongoDB shell version is 3.4.18 and npm installed mongodb module is 3.1.10.
Try inserting your record without creating the collection, as insertOne will automatically create the collection if it does not exist.
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';
MongoClient.connect(url, {useNewUrlParser: true}, function(err, db){
if(err) throw err;
var dbo = db.db('mydb');
var myObj = [{name: 'Company Inc', address: 'Highway 37'}];
var collection = db.collection('Customers');
collection.insertOne(myObj, function(err, res){
if(err) throw err;
console.log('1 document inserted!');
db.close();
});
});
https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/
just check the case of letter o in your insertOne function ..

NodeJs And MongoDB

db.getCollection('Leave').find({},{_id:0 ,
Can_It_Be_carry_forwarded:1})
this is working perfectly in the MongoDb Client CMD But not in the Below Code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/Chatbot_Project";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Chatbot_Project");
dbo.collection('Leave').find({}, {Can_It_Be_carry_forwarded:1}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
db.close();
})
});
Your problem is the find method, you are missing the projection field.
If you want to retrive only the Can_It_Be_carry_forwarded field you need the following: {projection:{Can_It_Be_carry_forwarded:1, _id: 0}} as the second argument.
Solution from a similar question: https://stackoverflow.com/a/48294672/4120554
Documentation: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
Try this:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/Chatbot_Project";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Chatbot_Project");
dbo.collection('Leave').find({},{projection:{_id: 0, Can_It_Be_carry_forwarded:1}}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
db.close();
})
});

Cannot insert document MongoDB database

I am not able to insert data into MongoDB database using insert method in Nodejs.
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
if (err) throw err;
// db gives access to the database
const myDb = db.db('learnyoumongo');
var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
docs.insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
})
db.close();
}
There is no output coming and connection to the data base is successful but no insertion of data is happening.
Try this will work for you .
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, dbobj) {
if (err) throw err;
// db gives access to the database
// const myDb = dbobj.db('learnyoumongo').collection('docs');
// var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
dbobj.db('learnyoumongo').collection('docs').insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
dbobj.close();
})
})
I figured out what the problem is. Seems like I forgot to add a parenthesis in the end:
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
if (err) throw err;
// db gives access to the database
const myDb = db.db('learnyoumongo');
var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
docs.insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
})
db.close();
})
You can use the following code to insert data into MongoDB using nodejs.
var mongo = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/learnyoumongo";
mongo.connect(url, function(err, db) {
if (err) throw err;
//access to the database
var myobj = { firstname: "Jhon", lastname: "Mackey" };
db.collection("docs").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("Data inserted");
db.close();
});
});

Cannot read property 'collection' of null

Here is my code
// Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log('we are connected');
}
var k ='testt';
var collection = db.collection(k);
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];
collection.insert(doc1);
collection.insert(doc2, {w:1}, function(err, result) {});
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});
});
and it is is showing this error "Cannot read property 'collection' of null".
The issue is you are directly calling db.collection irrespective of whether db connection is successful or not. You need to check whether there is an error in db connection. db.collection works only when the DB connection is successful. Check below example for better understanding
MongoClient.connect('mongodb://localhost:27017/test',function(err,db){
if(err)
{
console.log(err);
}
else
{
console.log("Connected to db");
db.collection('testt').insert({"doc1":"hello"},function(err,data){
if(err)
{
throw(err);
}
else
{
console.log("sucessfuly inserted");
}
})

Connect to MongoDB with authentication using Node JS

I am trying to connect to MongoDB with user/password , this is what I did so far:
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://${host}:27017/${db}", function(err, db) {
if(!err) {
console.log("successfully connected to the database");
}else{
console.log("Error on connecting... aborting and exiting");
return console.dir(err);
throw err;
}
db.authenticate('username', 'password', function(err, res) {
console.log("reached here");
});
});
Now I am trying to login inside the data base in order to be able to get inside Mongo Database's collections, how can I do that?
Thanks!
You can perform CURD operations like following:
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://${host}:27017/${db}", function(err, db) {
if(!err) {
console.log("successfully connected to the database");
//here you can perform operation
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
collection.insert(doc1);
}else{
console.log("Error on connecting... aborting and exiting");
return console.dir(err);
throw err;
}
db.authenticate('username', 'password', function(err, res) {
console.log("reached here");
});
});

Resources