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

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

Related

TypeError: login.findOne(...).toArray is not a function

I have this function, whcih bascially gets the usernmae and password of the users input from the front-end form, and then checks it in mongodb:
app.post('/login', (req, res, next) => {
var username = req.body.username;
var password = req.body.password;
//connecting to the mongo client
client.connect().then (() => {
//defining database name and collection
const database = client.db("myFirstDatabase");
const login = database.collection("login");
//connecting to the mongo client
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
//finding all documents inside array
login.findOne({"username": username}).toArray(function(err, result) {
if (err) throw err;
result.forEach(results =>
bcrypt.compare(password, results.password, function(err, result) {
if (result === true) {
req.session.loggedin = true
next()
} else {
res.redirect('/login')
}
})
);
db.close();
});
});
})
})
however, it is giving me this error:
TypeError: login.findOne(...).toArray is not a function
i've never encountered this error before. how do i fix this?
Try this way
login.findOne({"username": username}, function(err,user)
{ console.log(user); });

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

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>

Mongo DB make connection outside of post?

I am using MongoDB to insert a record into the database, every time the post method is called. I know I do not want to connect to the db inside of the post function every time, but this is giving me errors? How can I correct this?
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db = function() {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
}
app.post('/rsvp', function (req, res) {
var item ={
name: req.body.name,
attending: req.body.attending,
};
insertItem(item);
res.sendFile(path.join(__dirname + '/confirm.html'));
})
function insertItem(item){
db.collection('rsvpList').insertOne(item, function(err, result){
assert.equal(null, err);
})
}
I am getting this error:
TypeError: Object function () {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
} has no method 'collection'
at insertItem (C:\Users\A587092\Documents\weddingWebsite\server.js:53:8)
at app.listen.host (C:\Users\A587092\Documents\weddingWebsite\server.js:38:4)
at Layer.handle [as handle_request] (C:\Users\A587092\Documents\weddingWebsite\node_modules\express\lib\router\layer.js:95:5)
The problem is your db does not point to the Mongo instance rather to a function!
Try this -
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db;
mongo.connect(url, function(err, connectedDB){
if (!err){
db = connectedDB;
}
});
You couldn't simply return a value from an asynchronous method:
You should use a callback function:
var connectDb = function(url, cb) {
mongo.connect(url, function(err, db){
if ( err ) {
cb( err );
}
cb(null, db);
});
};
Usage:
function insertItem(item) {
connectDb(url, function(error, db) {
if ( error ) {
throw error;
}
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
});
}
Or a promise:
var connectDb = function(url) {
return new Promise(function(resolve, reject) {
mongo.connect(url, function(err, db){
if ( err ) {
reject(err);
}
resolve(db);
});
});
};
Usage:
function insertItem(item) {
connectDb(url)
.then(function(db) {
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
}, function(err) {
throw err;
});
}
I change the function name from db to connectDb because we want to connect to db and then doing something after connecting. and this way your code reads well.
Also note that here also your insertItem function doing an asynchronous task so if you need the result outside of this function you should implement a similar approach, i leave it to you ;)

How to reference a connection to MongoDB in NodeJS [duplicate]

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

Resources