running simple mongodb on c9.io but getting error - node.js

var MongoClient = require('mongodb').MongoClient;
//basic mongodb code
// Connect to the db
//create a new database called test
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
db.collection('test', function(err, collection){
if(err) console.log(err);
else console.log(collection);
});
db.collection('test', {w:1}, function(err, collection){
if(err) console.log(err);
else console.log(collection);
});
db.createCollection('test', function(err, collection){
if(err) console.log(err);
else console.log(collection);
});
db.createCollection('test', {w:1}, function(err, collection){
if(err) console.log(err);
else console.log(collection);
});
});
The error being shown is:
node index.js
/home/ubuntu/workspace/basic_version/node_modules/mongodb/lib/mongo_client.js:799
throw err;
^
TypeError: db.collection is not a function
at /home/ubuntu/workspace/basic_version/index.js:7:6
at args.push (/home/ubuntu/workspace/basic_version/node_modules/mongodb/lib/utils.js:405:72)
at /home/ubuntu/workspace/basic_version/node_modules/mongodb/lib/mongo_client.js:271:5
at connectCallback (/home/ubuntu/workspace/basic_version/node_modules/mongodb/lib/mongo_client.js:935:5)
at /home/ubuntu/workspace/basic_version/node_modules/mongodb/lib/mongo_client.js:796:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

Related

Delete particular data in mongodb using node js

How can I delete particular data in mongodb using node.js ?
router.post('/deletedata', (req, res) => {
console.log("deleted values are",req.body.id)
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mohan");
var myquery = req.body.id;
console.log("myquery value is:", myquery)
dbo.collection("customers").remove({myquery}, function(err, obj) {
if (err) throw err;
db.close();
});
});
res.json({
statusCode: 200,
result: "success",
})
}
);
export default router;
I got particular id from React hooks crud app , So i can see the id in node js but it does not delete the that particular id data in mongoDB
Your query will only delete documents with myquery: passedId
I bet query should look like {_id: myquery}
dbo.collection("customers").remove({_id: myquery}, function(err, obj) {
if (err) throw err;
db.close();
});
dbo.collection("customers").remove(myquery, function(err, obj) {
if (err) throw err;
db.close();
});
try using delete({query}) or deleteMany({query})

Mongo db returning empty results

My code:
MongoClient.connect(gloabl_vars.db.mongo.url,function(err, db) {
if(err) { throw err; }
var dbo=db.db("profilemanager");
var mquery={_id:'123454'};
db.collection('userinfo').find(mquery,{'_id':0,'subscriptions':1}).toArray(function(err,result){
if(err) throw err;
console.log(result);
});
});
}
am able to get the result from Robo3T mongo client but same is returning null through nodejs.
Robo3T:
db.getCollection('userinfo').find({_id:'66613'},{'_id':0,'subscriptions':1});
You are searching a record by {_id:'66613'} in Robo3T but your sample is {_id:'123454'} in node.js. Also projection in node.js find is not in this way. Try below Snippet
MongoClient.connect(gloabl_vars.db.mongo.url,function(err, db) {
if(err) { throw err; }
var dbo=db.db("profilemanager");
var mquery={_id:'66613'};
db.collection('userinfo').find(mquery).project({'_id':0,'subscriptions':1}).toArray(function(err,result){
if(err) throw err;
console.log(result);
});
});
}

MongoDB: Conditionally delete DB entries depending on changes in linked file

E.g.: FileName = Lakshmikantha.html and Username also Lakshmikantha. If that Lakshmikantha.html file is modified then I want to delete that user from DB.
app.js
app.post('/home',urlencodedParser,function(req1,res1){
var filname = req1.body.username;
var str;
var originalfile;
var flag;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("users").insert(req1.body, function(err, res) {
if (err) throw err;
console.log("user "+req1.body.username+ " inserted");
// db.close();
});
dbo.collection("users").find().toArray(function(err, result) {
if (err) throw err;
res1.render('home',{user:result});
// db.close();
});
watcher.on('change', function(path1) {
var filename = path.basename(path1);
originalfile = pathParse(filename).name;
str = originalfile.toString();
console.log(originalfile);
flag = true;
});
db.close();
});
if(flag){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("users").remove({"username":str}, function(err, obj) {
if (err) throw err;
console.log("1 document deleted" + str);
});
db.close();
});
}
});
/*MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
//Delete the "customers" collection:
dbo.collection("users").drop(function(err, delOK) {
if (err) throw err;
if (delOK) console.log("Collection deleted");
db.close();
});
});*/
Here I am inserting users to DB through loginpage and if particular filename with that username appears, I want to delete the entry from the DB.

Mongodb: how to load data after it's been saved?

How to load all of the documents within a database right after a new document has been added to the database?
app.get('/ajax', function(req, res) {
var itemOne = new Todo({item: req.query.item}).save(function(err,data){
if (err) throw err;
});
Todo.find({}, function(err1, data1){
if (err1) throw err;
res.send(data1);
});
});
app.get('/ajax', function(req, res) {
var itemOne = new Todo({item: req.query.item}).save(function(err,data){
if (err) throw err; //Find Records right here
Todo.find({}, function(err1, data1){
if (err1) throw err;
res.send(data1);
});
});});
In your code "save" function and "find" function will run asynchronously so finding inside the callback function will get u all the results

MongoError: Connection Closed By Application using node.js driver

Hi guys, need some help , have a problem when run this code :
MongoClient.connect('mongodb://localhost:27017/school',function (err,db) {
if(err) throw err;
var query = {};
var cursor = db.collection('students').find(query);
cursor.each(function (err,doc) {
if(err) throw err;
if(doc==null) return db.close();
//Processing doc to update
db.collection('students').update({"_id":doc["_id"]},{$set:{"scores":doc.scores}},function (err,result) {
if(err) throw err;
});
});
it works, but then appear this message =(:
MongoError: Connection Closed By Application
MongoClient.connect('mongodb://localhost:27017/school',function (err,db) {
if(err) throw err;
var query = {};
var cursor = db.collection('students').find(query);
cursor.each(function (err,doc) {
if(err) throw err;
if(doc==null) return db.close();
//Processing doc to update
db.collection('students').update({"_id":doc["_id"]},{$set:{"scores":doc.scores}},function (err,result) {
if(err) throw err;
db.close(); //this line was missing!!!!!!!!!!!!!!!!!!!!!!!!!!!!
});
});

Resources