I'm unable to find by _id on mongodb - node.js

I'm trying to find() by _id using Node.js and MongoDB.
I'm able to show objects in the database when using an alternative parameter, or using no parameters at all. Here's my code and results to show that:
mongo.connect(url, function(err, db){
if (err) throw err;
db.collection('listings').find().toArray(function(err, result){
if (err) throw err;
console.log(result);
db.close();
});
});
The results I get back are this:
[{"_id":"5a1ff1ac32fe0a2bd966be1e","title":"hi","price":"5"},{"_id":"5a207cea2f119cbd6a5fa688","title":"hello","price":"10"}]
When I modify the code to find the results using the title "hi" I get back this:
[{"_id":"5a1ff1ac32fe0a2bd966be1e","title":"hi","price":"5"}]
using the following code:
mongo.connect(url, function(err, db){
if (err) throw err;
db.collection('listings').find({'title': 'hi'}).toArray(function(err, result){
if (err) throw err;
console.log(result);
db.close();
});
});
However when I try to sort by _id using this code:
mongo.connect(url, function(err, db){
if (err) throw err;
db.collection('listings').find({'_id': '5a1ff1ac32fe0a2bd966be1e'}).toArray(function(err, result){
if (err) throw err;
res.send(result);
db.close();
});
});
The results I get back is
[]
The question is: how do I find by _id so that when I use _id I can get back results for that specific _id?

'5a1ff1ac32fe0a2bd966be1e' is a string.
_id is of type ObjectId.
You can make an object id with ObjectID('5a1ff1ac32fe0a2bd966be1e'). You can require the function like this:
const ObjectID = require('mongodb').ObjectID;
Here is the documentation.

Related

insertedID when i was using then it not show in nodejs

con.connect(function(err){
if(err) throw err;
var sql="Insert into Employee(name) values('Pravin')";
con.query(sql, function(err, result){
if(err)throw err;
/*Use the result object to get id*/
console.log("1 record inserted , ID"+result.insertedID);
});
});
1 record inserted , IDundefined
not able get Id number in this

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

Mongo db returning empty results

My code:
MongoClient.connect(gloabl_vars.db.mongo.url,function(err, db) {
if(err) { throw err; }
var dbo=db.db("profilemanager");
var mquery={_id:'123454'};
db.collection('userinfo').find(mquery,{'_id':0,'subscriptions':1}).toArray(function(err,result){
if(err) throw err;
console.log(result);
});
});
}
am able to get the result from Robo3T mongo client but same is returning null through nodejs.
Robo3T:
db.getCollection('userinfo').find({_id:'66613'},{'_id':0,'subscriptions':1});
You are searching a record by {_id:'66613'} in Robo3T but your sample is {_id:'123454'} in node.js. Also projection in node.js find is not in this way. Try below Snippet
MongoClient.connect(gloabl_vars.db.mongo.url,function(err, db) {
if(err) { throw err; }
var dbo=db.db("profilemanager");
var mquery={_id:'66613'};
db.collection('userinfo').find(mquery).project({'_id':0,'subscriptions':1}).toArray(function(err,result){
if(err) throw err;
console.log(result);
});
});
}

Mongodb: how to load data after it's been saved?

How to load all of the documents within a database right after a new document has been added to the database?
app.get('/ajax', function(req, res) {
var itemOne = new Todo({item: req.query.item}).save(function(err,data){
if (err) throw err;
});
Todo.find({}, function(err1, data1){
if (err1) throw err;
res.send(data1);
});
});
app.get('/ajax', function(req, res) {
var itemOne = new Todo({item: req.query.item}).save(function(err,data){
if (err) throw err; //Find Records right here
Todo.find({}, function(err1, data1){
if (err1) throw err;
res.send(data1);
});
});});
In your code "save" function and "find" function will run asynchronously so finding inside the callback function will get u all the results

Updating each element in MongoDB database in for loop

I have an array of userIDs (MongoDB Objectids)which I want to iterate through and for each one, find its user entry in my MongoDB database of users, and update it, say modify the user's age. Then only when every user has been updated, do I want to say res.send(200); in my Node.js Express app.
I started out with the following code which is just plain wrong because of the asynchronous calls to findById:
for (var i = 0; i < userIDs.length; i++) {
var userID = userIDs[i];
User.findById(userID, function (err, user) {
if (err) throw err;
// Update user object here
user.save(function (err, user) {
if (err) throw err;
res.send(200);
});
});
}
Any ideas how I can do this? Is there perhaps a synchronous version of findById? Or perhaps a way to map through the array and apply a function to each element?
Thanks!
I think you want the forEach method of npm's async module. It would look something like this:
async.forEach(userIDs, function(id, callback) {
User.findById(id, function(err, user){
if(err) throw err;
user.save(function(err, user){
if(err) throw err;
callback();
}
}, function(err){
if(err){
throw err;
} else {
res.send(200);
}
}
}
The best way is to use promises.
An example with Q#all:
var q = require('Q');
var promises = userIDs.map(function(userID){
var deferred = q.defer();
User.findById(userID, function (err, user) {
if (err) return deferred.reject(err);
// Update user object here
user.save(function (err, user) {
if (err) return deferred.reject(err);
deferred.resolve(user);
});
});
return deferred.promise;
});
q.all(promises)
.then(function(users){
res.json(users);
})
.fail(function(err){
res.send(500,err);
});

Resources