cannot insert json object directly to mongodb using nodejs [duplicate] - node.js

I'm new with nodeJS and MongoDB.
I have this code:
var fs = require('fs');
var mongojs = require('mongojs');
var db = mongojs('monitor', ["configurations"]);
fs.readFile('json/object1.json', 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
db.configurations.insert(data, function(err, doc) {
console.log(data);
if(err) throw err;
});
});
no data insered to the mongodb, and I've got no error.
the both console.log(data) print the json string as well.

Try to parse it as JSON before inserting it into the document
fs.readFile('json/object1.json', 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
var json = JSON.parse(data);
db.configurations.insert(json, function(err, doc) {
console.log(data);
if(err) throw err;
});
});

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();
});

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})

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.

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();
});
});

Resources