nodejs mongodb not deleteing based on id - javascript

Can you please help me with this code. This code is not deleting the value from MongoDB, while I am running this url : http://localhost:3000/delete/57c6713455a6b92e105c5250.
I am getting this response: {"lastErrorObject":{"n":0},"value":null,"ok":1}, but not deleting .
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': uid}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});

In MongoDB you query a document id(_id) by using the ObjectId constructor and not the ObjectId's string. Thus the query needs to be: { '_id': ObjectId(uid) }.
Example
var mongoClient = require('mongodb').MongoClient;
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
mongoClient.connect("Your connection string", function(err, db) {
var query = {
_id: ObjectId("id_string") // Important to notice
};
var collection = db.collection('your collection');
collection.find(query, function(err, docs) {
console.log(err, docs);
});
});
Suggestion
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
//Add object id to query object
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid)}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});

Yes. thank you i figured where i did wrong. see below correct answer.
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid) }, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});

This response means, your query is executing properly "OK":1, but the find query is unable to find any doc to delete it.
So before using "findOneAndDelete" use only "findOne" and log the response to check weather you that doc or not.

Related

Mongo DB is not updated by id

i'm trying to update mongo db document with mongo db driver on node js, the log show that it's updated but the data is not updated, i'm trying to get the data to get updated with id document and the document is not updated, but when i use another field as a variable to search the document, the document is updated.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://192.168.1.200:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("monitoring");
var myquery = { _id : "62e5e171f38e161d6e905772" };
var newvalues = { $set: { status: "1" } };
dbo.collection("hosts").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
Picture of the data:
_id property in MongoDB is not of type String, it's of type ObjectId. Try this:
const ObjectID = require('mongodb').ObjectID;
...
const myquery = { _id : new ObjectId("62e5e171f38e161d6e905772") };

Cannot retrieve all entries from MongoDB collection

i'm trying to retrieve all entires from mongo yet I keep on getting an error that I couldn't find any while having there are some entries.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';
tryMongo();
function tryMongo() {
MongoClient.connect(url, (err, client) => {
if (err) return console.log('Cannot connect to DB');
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('toy');
collection.find().toArray((err, docs) => {
if (err) return console.log('cannot find toys');
console.log('found these:');
console.log(docs);
});
client.close();
});
}
this is the error i'm getting :
Server listening on port 3030!
Connected successfully to server
cannot find toys
I have also added a picture of mongo
appreciating any kind of help!
You are closing mongo connection before you get response from server. Move client.close(); inside toArray callback.
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'toy_db';
tryMongo();
function tryMongo() {
MongoClient.connect(url, (err, client) => {
if (err) return console.log(err);
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('toy');
collection.find().toArray((err, docs) => {
if (err) {
console.log(err);
} else {
console.log('found these:');
console.log(docs);
}
client.close();
});
});
}

Update user information

Tried this for updating user information , only phone number but it's not getting update.
router.post('/edit', checkAuth, function (req, res, next) {
console.log(req.userData.userId)
User.update({_id: req.userData.userId}, {$set:req.userData.phoneNo}, function (err){
if (err) {
console.log(err);
}
res.status(200).send(req.userData);
});
});
My user controller const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
And then I am authenticating by passing jwt on this field
phoneNo: user[0].phoneNumber
The auth-token verifies and decode the fields
const token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_KEY)
req.userData = decoded;
Update is not working and getting error message Invalid atomic update value for $set. Expected an object, received string .
first of all, you should use PATCH-method - because you are updating only one item in existed object, in body you should send id of user and new value of certain value. If you use mongoose you can try it
User.findOneAndUpdate({ _id: id }, updatedItem, { new: true }, (err, doc) => {
if (err) return res.send(err.message)
if (doc) return res.send(doc);
})
const id = req.body._id;, if you dont use mongoose you should try findAndModify method
Your code
User.update({_id: req.userData.userId}, {$set:req.userData.phoneNo}
Correct code:
User.update({_id: req.userData.userId}, {$set:{phoneNumber:req.userData.phoneNo}}
Try this method:
User.findByIdAndUpdate(req.userData.userId, { $set:{phoneNumber:req.userData.phoneNo}}, { new: true }, function (err, user) {
if (err) console.log(err);
res.send(user);
});

In nodejs collection.find() is not fetching values from Mongodb collection.It returning nothing

app.get('/render', function(req, res) {
MongoClient.connect(dburl, function(err, db) {
if (err) throw err;
var collection = db.collection('shopping_list');
collection.find().toArray(function(err, result) {
res.send({result :result});
});
db.close();
});
});
In nodejs collection.find() is not fetching values from Mongodb collection.It returning nothing
In nodejs collection.find() is not fetching values from Mongodb collection.It returning nothing
exports.index = function(req, res) {
var queryObj = {};
UserModel.find(queryObj)
.exec(function(err, users) {
if (!users) {
console.log("users not found");
}
if (!err) {
console.log("number of users",users.length);
} else {
console.log("err",err);
}
});
};

How to call mongodb collection getall by node.js?

I wanna take the whole list of notifies from mongo db but it returns empty([]) array also I know that i need callback or shorter way of it . Do you have any idea for collecting any data from mongodb by node.js? If I call this /Notifies method (http://127.0.0.1:5000/Notifies)
var MongoClient = require('mongodb').MongoClient;
var express = require("express");
var app = express();
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
});
return res.json(arr);
});
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log("Listening on " + port);
})
Don't use for docs.each instead of this use .toArray so it will return directly a array and then use Json.stringify to convert it into json string array
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
coll.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else {
res.send(JSON.stringify(result));
}
})
});
The problem is you are returning the empty array from within the function, before the actual DB operation occurs. You need to move the line return res.json(arr);
into the find function:
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
console.log(docs);
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
return res.json(arr);
});
});
});
Also, for future use, do not reuse variable names in nested functions (you have 3 functions that use the variable err).

Categories