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");
});
});
Related
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();
});
I can't delete values in mongodb using reactjs and node js
this is my react hooks axios post method send to node js
const deleteUser = id => {
var data={"id":id}
axios.post('http://localhost:8010/api/social/deletedata',data)
.then((res) => {
console.log('response',res);
})
.catch((error) => {
console.log('error block called',error);
})
setEditing(false)
setUsers(users.filter(user => user.id !== id))
}
this is my node js code
router.post('/deletedata', function(req, res, next) {
console.log("deleted values are",req.body)
//var id = req.body;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var myId = JSON.parse(req.body.id);
db.collection('customers').deleteMany({"_id": objectId(myId)}, function(err, result) {
assert.equal(null, err);
console.log('Item deleted');
db.close();
});
});
});
I think you need to pass the _id as ObjectID, try like this
var mongodb = require('mongodb');
router.post('/deletedata', function(req, res, next) {
console.log("deleted values are",req.body)
//var id = req.body;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('customers').deleteMany({"_id": new mongodb.ObjectID(req.body.id)},
function(err, result) {
assert.equal(null, err);
console.log('Item deleted');
db.close();
});
});
});
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();
});
});
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");
}
})
This question already has an answer here:
NodeJS Can't Access Variable Inside Callback
(1 answer)
Closed 7 years ago.
I have the following code:
var db;
MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
if(!err) {
console.log("We are connected");
}
db = database;
});
db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
}
});
And I get the following output:
We are connected
TypeError: Cannot call method 'collection' of undefined
var db;
MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
if(!err) {
console.log("We are connected");
db = database;
db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
}
});
}
});
Connect method is asyncrone, so your db variable will be initialized much later, then you start using it. Try this code:
MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
if(err) {
// Here, it may be better to interrupt further work in case of error
console.log('fail', err);
return;
}
var db = database;
db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
if(!err){
console.log("written");
}
});
});
EDIT
A full example of nodejs server, taken from here
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
if(err) throw err;
db = database;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get("/", function(req, res) {
db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});