Cannot get data-id in nodejs and mongodb - node.js

I'm a newbie. I created my first nodejs project with mongodb. And i get some errors.
Actually, "data-id" attribute cannot get id string in database. There is my index.pug.
if (data.length)
each item in data
tr
td #{item['_id']}
td #{item['name']}
td #{item['email']}
td
a.btn.btn-primary.editlink(href='javascript:void(0)', data-id = '#{item["_id"]}') Edit
|
a.btn.btn-danger(href='/delete?id=#{item["_id"]}', onclick='return confirm("Are you sure ?")') Delete
script.
$(function() {
$('.editlink').on('click', function(){
var id = $(this).data('id');
$.ajax({
method: "GET",
url: "/fetchdata",
data: { id: id },
}).done(function( data ) {
$('#id').val(data[0]['_id']);
$('#name').val(data[0]['name']);
$('#email').val(data[0]['email']);
$("#subbtn").val('Edit');
$('#form1').attr('action', '/edit');
});
});
});
My index.js
router.get('/', function(req, res, next) {
MongoClient.connect(dburl, function(err, client) {
if(err) { console.log(err); throw err; }
data = '';
var db = client.db(dbname);
db.collection('products').find().toArray(function(err, docs){
if(err) throw err;
res.render('index', {data: docs});
console.log(docs);
client.close();
});
});
});
router.get('/fetchdata', function(req, res, next) {
var id = req.query.id;
MongoClient.connect(dburl, function(err, client) {
if(err) { console.log(err); throw err; }
data = '';
var db = client.db(dbname);
db.collection('products').find({_id: new mongodb.ObjectId(id)}).toArray(function(err, docs){
if(err) throw err;
res.send(docs);
client.close();
});
});
});
I updated my script with $(document).ready(function(){} ) but it doesn't work .

I think may be the problem is in Edit part
you have to set data-id= item['_id']
as
td
a.btn.btn-primary.editlink(href='javascript:void(0)', data-id = item["_id"]) Edit
|
a.btn.btn-danger(href='/delete?id='+#{item["_id"]}, onclick='return confirm("Are you sure ?")') Delete

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

how to delete data from react crud using node js to mongoDB

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

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()...

How to delete a particular row in Node.js and express

How can I delete data from a list in Node.js, using express and ejs view? I have tried, but it's not working. I am using mongodb.
Here is what I have done so far but it's not working.
router.post('/delete', function(req, res, next) {
var id = req.body.id;
mongodb.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('profile').deleteOne({ "_id": objectId(id) }, function(err, result) {
console.log('Item deleted');
db.close();
});
});
res.redirect('/userlist');
});
and ejs (view) code is:
<td>Delete</td>
below code is works but when I press Delete, it deletes all the row. Here I used get intead of post
router.get('/delete', function(req, res, next) {
mongodb.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('profile').deleteOne(function(err, result) {
console.log('Item deleted');
db.close();
});
});
res.redirect('/userlist');
});
If you want to use a get request, it can be done like this:
router.get('/delete/:id', function(req, res, next) {
var id = req.params.id;
mongodb.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('profile').deleteOne({ "_id": objectId(id) }, function(err, result) {
console.log('Item deleted');
db.close();
});
});
res.redirect('/userlist');
});
Now you need to request something like this:
<td>Delete</td>

Keep getting Error: Can't set headers after they are sent

So I am trying out my code for updating and showing it to the user. Basically it is able to do what I need to do but after performing it I get this error
C:\Users\tester01_2\myproject\node_modules\mongodb-core\lib\cursor.js:174
throw err;
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
at ServerResponse.header (
C:\Users\tester01_2\myproject\node_modules\express\lib\response.js:725:10)
at ServerResponse.send
(C:\Users\tester01_2\myproject\node_modules\express\lib\response.js:170:12)
at C:\Users\tester01_2\myproject\dbUpdate.js:13:14
at C:\Users\tester01_2\myproject\dbUpdate.js:28:5
at handleCallback (C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:171:5)
at nextFunction (C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:682:5)
at Cursor.next [as _next]
(C:\Users\tester01_2\myproject\node_modules\mongodb-
core\lib\cursor.js:692:3)
at loop
(C:\Users\tester01_2\myproject\node_modules\mongodb\lib\cursor.js:694:8)
at _each
(C:\Users\tester01_2\myproject\node_modules\mongodb\lib\cursor.js:741:16)
This is my code
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
module.exports = {
postCollection : function(req, res){
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
updateRecord(db, req, function(doc) {
return res.send('Record Found. Now updating this document...' +
itemDescrip + ' Record Updated. This is the new record ' + doc )
res.end();
db.close();
});
});
}
}
var updateRecord = function(db, req, callback) {
var cursor = db.collection('documents').find({'Item Description':
req.body.itemDescrip, 'Issued QTY': req.body.issueQty})
cursor.each(function(err,doc){
assert.equal(err, null);
if(doc != err){
console.log('Successfully queried');
console.log(doc);
callback(JSON.stringify(doc));
} else{
throw err;
}
});
db.collection('documents').updateMany(
{ 'Item Description': req.body.itemDescrip},
{
$set: { 'Issued QTY': req.body.issueQty }
},function(err, results) {
console.log(results);
console.log('Done');
console.log(results);
});
};
I think it has to do with my res due to all the threads I have seen being res being in a wrong position but I need to put my res.send there so that it can use doc. Is there any way to solve this problem? Thanks.
Firstly, you should remove return in front of res.send().
Secondly, in updateRecord function, the callback function shouldn't be called in a loop, it will execute multiple times. And you close the db before you execute updateMany.
If you want to send doc, you should use a temp array to hold the doc, and pass it to res when you finish all logics in updateRecord.
If I understand you correctly, following is my modification of your codes,
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';
var updateRecord = function(db, req, callback) {
db.collection('documents').updateMany({ 'Item Description': req.body.itemDescrip }, {
$set: { 'Issued QTY': req.body.issueQty }
}, function(err, results) {
if (err) return callback(err);
console.log('Done');
console.log(results);
var cursor = db.collection('documents').find({
'Item Description': req.body.itemDescrip,
'Issued QTY': req.body.issueQty
});
var temp = [];
cursor.each(function(err, doc) {
if (err) {
return callback(err);
}
console.log('Successfully queried');
console.log(doc);
temp.push(JSON.stringify(doc));
});
callback(null, temp);
});
};
module.exports = {
postCollection: function(req, res) {
var issueQty = req.body.issueQty;
var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
if(err) {
res.send(err);
res.end();
db.close();
return;
}
updateRecord(db, req, function(err, docs) {
if(err){
res.send(err);
}
else{
res.send(docs);
}
res.end();
db.close();
});
});
}
}

Resources