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

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>

Related

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

Cannot get data-id in nodejs and mongodb

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

Unable to delete data from mongoDB

Im using POSTMAN to delete contact using id and it returns
{
"n": 0,
"ok": 1
}
This is my delete code so far
router.delete('/contact/:id', (req, res, next) => {
contact.remove({ _id: new objectId(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
You need to pass the _id value as an ObjectID, not a string:
var mongodb = require('mongodb');
router.delete('/contact/:id', (req, res, next) => {
contact.deleteOne({ _id: new mongodb.ObjectID(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
id !== _id
change :id in your route to :_id and you should be fine.

Query multiple mongodb collections in node app using Mongoose async

In my node.js app I want to query multiple mongodb collections in a series using mongoose with the async plugin based on result from the first callback in the series.
So far I have this working code but I'm sure there is a better way of doing it async:
router.route('/project/:projectId')
.get(function(req, res) {
var getProjectDetails = function(cb) {
models.Project.findById(req.params.projectId, function(err, project) {
if(err)
res.send(err);
models.Media.find({'project_code' : project.code }, function(err, media) {
cb(null, {'project' : project, 'media': media})
});
})
}
async.parallel([getProjectDetails], function(err, result) {
res.render('details', {data: result});
});
});
As you can see I want to find all entries from the Media collection where project_code equals code from Project collection.
How can I acvhieve this without nesting my mongoose-querys?
Why do you need async in this? I hope this will work.
router.route('/project/:projectId')
.get(function(req, res) {
models.Project.findById(req.params.projectId, function(err, project) {
if(err)
return res.send(err);
models.Media.find({'project_code' : project.code }, function(err, media) {
if(err)
return res.send(err);
return res.render('details', {data: {'project' : project, 'media': media}});
});
});
});

Nodejs Rest API with mongoose and mongoDB

I have this rest API on nodejs as follows
router.route('/api/Customers')
.post(function(req, res) {
var Customer = new Customer();
Customer.name = req.body.name;
Customer.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Customer created!' });
});
})
.get(function(req, res) {
Customer.find(function(err, Customers) {
if (err)
res.send(err);
res.json(Customers);
});
});
router.route('/api/Customers/:Customer_id')
.get(function(req, res) {
Customer.findById(req.params.Customer_id, function(err, Customer) {
if (err)
res.send(err);
res.json(Customer);
});
})
.put(function(req, res) {
Customer.findById(req.params.Customer_id, function(err, Customer) {
if (err)
res.send(err);
Customer.name = req.body.name;
Customer.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Customer updated!' });
});
});
})
.delete(function(req, res) {
Customer.remove({
_id: req.params.Customer_id
}, function(err, Customer) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
How can I create endpoints for specific fields ? For example if I want to GET results for CustomerName, CustomerZip, etc .. Do I have to create separate end points for each field?
Are you using express.js as framework? In this case you can put optional params in your route, for example:
router.route('/api/Customers/:Customer_id?')
.post(function(req, res) {
...
})
.get(function(req, res) {
...
});
});
in this way :Customer_id will be optional and you can manage logic inside your route.
This is a working example:
app.route('/test/:param1?/:param2?')
.get( function(req, res, next) {
res.json({
'param1' : req.params.param1,
'param2' : req.params.param2
});
});
app.listen(8080);
this route supports:
/test
/test/1
/test/1/2
inside response you can see value of this params, I don't know how pass only param2 without param1.

Resources