using a parameter in mongoDb .find() query [duplicate] - node.js

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 3 years ago.
This works, but once I change the 123 to req.params.userId, I obtain an empty array from the GET request.
router.get("/:userId", async (req, res) => {
const posts = await loadPostCollection();
console.log(req.params.userId) //>>>123
const info = await posts
.find({
userInfo: {
userId: 123, //req.params.userId doesn't work
notes: []
}
})
.toArray();
res.send(await info);
});
edit: the question was not how to convert string to num or num to string, but rather help with finding out what's wrong with the code. Therefore, not duplicate.

Oh I got it, req.params.userId is a string while userId is expecting a number.

It's because of string and number. Try converting the req.params.userId to number and it should work!

Related

Split users ids for database query [duplicate]

This question already has answers here:
How to construct a REST API that takes an array of id's for the resources
(6 answers)
How to get multiple document using array of MongoDb id?
(7 answers)
Closed 21 days ago.
The community is reviewing whether to reopen this question as of 21 days ago.
I'm trying to retrieve multiple users from a database, but I'm not sure how to make the query.
I get the IDs from the endpoint like this: localhost:1000/api/user/1,2,3,4 where 1,2,3,4 are the ids of 4 different users.
What I tried to do is to use .split() on the request but I am not able to solve it..
To get all the users I am using this function:
function GetAll(req, res){
userSchema
.find({},{_id:0, __v:0})
.then((data) => res.json(data))
.catch((error) => res.json({ msg: error }))
};
This is to retrieve a single user:
function GetUser(req, res){
const { id } = req.params // '1,2,3,4';
userSchema
.find({id}, {_id:0, __v:0})
.then((data) => res.json(data))
.catch((error) => res.json({msg: error }))
};
I tried to do the split() in GetUser, which only looks for a single user... Is there an easier way to solve it?
I tried something like this:
function GetUser(req, res){
const { id } = req.params;
const idSplited = id.split(",");
userSchema
.find({id}, {_id:0, __v:0})
.then((data)=> data = data.filter((item) => idSplited.includes(item.id)) = res.json(data))
.catch((error) => res.json({msg: error }))
};

How to fix querying issues with mongoose and express [duplicate]

This question already has answers here:
Can't find documents searching by ObjectId using Mongoose
(3 answers)
Closed 1 year ago.
I am still fairly new to dynamic routing and although it makes sense, I am having issue implementing it correctly. Below is a function I want to grab the user's purchases from the database and export it as a csv. I had it working on local mongoDB but when I moved to Atlas for hosting, it only grabs the first person listed in the database and not the person logged in. Could I get some guidance on why my req.params is not working. Thank you in advance.
(This route would fall under app.use(/profile, profile) in the server)
profile.js
// DOWNLOADING CSV OF PURCHASES
router.get("/purchased-items/:id", csvAbuseLimiter, (req, res) => {
if (req.isAuthenticated()) {
User.findOne({ id: req.query.id }, (err, foundUser) => {
if (foundUser) {
console.log(foundUser);
const userPurchases = foundUser.purchases;
const fields = ["name", "order", "duration", "asset"];
const json2cvsParser = new Parser({ fields });
try {
const csv = json2cvsParser.parse(userPurchases);
res.attachment(`${req.user.username}-purchases.csv`);
res.status(200).send(csv);
req.flash("success", "successful download");
} catch (error) {
console.log("error:", error.message);
res.status(500).send(error.message);
}
}
});
}
});
person logged in
What the route is pulling.
In the code provided you are using req.query.id and not req.params.id

Collection count using mongoose [duplicate]

This question already has answers here:
How to get all count of mongoose model?
(9 answers)
Closed 1 year ago.
I am trying to display the total registered users in the admin panel.
Below is my code to get the total count
exports.getcount = async (req, res) => {
Client.count({}, function (err, count) {
console.log("Number of users:", count);
res.status(200).json({
message: `Registered Clients ${count}`,
});
});
};
In my client schema, I have an isDeleted field that is either true or false. In my total count, I just want to return those clients which contain isDeleted:false.
Instead of .count(), which is deprecated (see here ), you could use .countDocuments({ isDeleted: false }).
countDocuments accepts a filter that will match documents in your database collection. Here are the docs

Delete an item in array within an array

Am I doing this correctly in the backend API? How would you delete an object inside an array within a parent array in the backend? I first found the main parent array index and then I found the object from tasks array using .tasks[index]. The question is how would I delete this in node? Tutorials I found uses req.params.id to delete an item but mine is more complicated.
exports.deleteTaskItem = async (req, res) => {
const taskindex = req.params.id;
const index = req.params.index;
try {
const taskfound = await Task.findById(taskindex);
const taskfounditem = await taskfound.tasks[index];
//code to type here
res.status(204).json({
status: "success",
data: null
});
} catch (err) {
res.status(404).json({
status: "fail",
message: err
});
}
};
I believe this piece of documentation would interest you:
https://docs.mongodb.com/manual/reference/operator/update-array/
And to specify, I believe you want to use the $pull operator.
Something like this:
const {id, index} = req.params;
await Task.findByIdAndUpdate(id,{
$pull: {
tasks: { _id: index }
}
});
(Disclaimer: I did not test this out this time, sorry. But it should be close.)
edit: Now when I reread the question I notice that you want to use the index. Personally I think it'd be easier to just add ids since you get that automatically if you use a sub-document. But if you insist on using index, maybe this answer can help:
https://stackoverflow.com/a/4970050/1497533
edit again:
It seems this helped getting a working solution, so I'll copy it in from comments:
taskfound.tasks.splice(taskindex, 1);
taskfound.markModified('tasks');
await taskfound.save();

How to find one object in mongodb [duplicate]

This question already has answers here:
MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update
(4 answers)
Closed 3 years ago.
I'm new to mongodb and am trying to compare a name typed from a input with a names saved in my collection and if there is this same name i want to increment "numberOfSearches" in database of this object name and if not let it create that one in collection. After all i don't know how to compare those names in "if", should i use Find method otherwise or there is other method for that?
app.post('/stronka', function(req,res){
var obj = {name: req.body.chosenCity, numberOfSearches: 1};
if(db.collection('miasta').find({name: obj.name})){
db.collection('miasta').updateOne(
{"name": obj.name},
{$inc: {"numberOfSearches": 1}}
)
res.redirect('/stronka');
console.log("first option");
}
else{
db.collection('miasta').insertOne(obj, function(err, result){
if(err) return console.log(err);
console.log('saved to database')
res.redirect('/stronka');
})
console.log("sec option");
}
})
One problem that you will likely run into here is that db.collection('...').find() will return an asynchronous Promise not a synchronous value. In order to use the result of the find(), you need to await it as such:
app.post('/stronka', async function(req,res){ <-- note the addition of the async keyword
var obj = {name: req.body.chosenCity, numberOfSearches: 1};
const result = await db.collection('miasta').find({ name: obj.name });
if (result) {
....
} else {
...
}
});
You will need to apply a similar principle to the updateOne and other calls to MongoDb, but I'll leave that as an exercise for you (:

Resources