Collection count using mongoose [duplicate] - node.js

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

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

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

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!

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 (:

Trying to sort not based on field, but from most recent to previous in mongoose [duplicate]

This question already has answers here:
mongoose: Sorting by id
(1 answer)
How does MongoDB sort records when no sort order is specified?
(2 answers)
Closed 4 years ago.
I'm trying to figure out how to sort my results by most recent to previous entries in MongoDb.
I'm using Node.JS and Express for my API and have the following end point:
router.route('/getbyowner/:ownerId')
.get(function(req, res) {
Alerts.find({ owner_id: req.params.ownerId }, function(err, alerts) {
if (err)
res.send(err);
res.json(alerts);
})
});
In the Mongoose docs I can see how you would sort based on a filed and apply asc or desc, like so:
// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });
But the object array returned doesn't have an index field I can sort on.
How is sorting in asc / desc done if not on a specific field?
I tried the following and this did not work:
router.route('/getbyowner/:ownerId')
.get(function(req, res) {
Alerts.find.sort({ _id: -1 , owner_id: req.params.ownerId }, function(err, alerts) {
if (err)
res.send(err);
res.json(alerts);
})
});

Issue in saving values in array in mongoose model using save() [duplicate]

This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 5 years ago.
I am trying to update a document in a collection. I am particularly trying to update an array of Strings.The following is my Schema
var sampleSchema= mongoose.Schema({
fullName : String,
email : String,
rolesTaken : [String],
});
I basically have an array of such schema's. I want to update the rolesTaken array for all of them.
So I did the following
var async = require('async');
var ATmapping = require('path to Schema');
ATmapping.find({},function(err,lists){
if(err){
console.log(err);
return;
}
if(lists.length > 0){
async.each(lists,function(list,callback){
if(!list.rolesTaken){
list.rolesTaken =[];
}
list.rolesTaken.push("Patient");
list.markModified('rolesTaken');
list.save(function(err,item){
if (err){
console.log(err);
}
console.log('Saved', item);
callback();
});
});
}
});
I have browsed a lot and the most popular solution was to add markModified. But it doesn't seem to work in my case.When I added mongoose.debug i got the following
atmappings.update({ _id: ObjectId("59074b127adeef0004b84ac3"), __v: 7 }, { '$set': { rolesTaken: [] }, '$inc': { __v: 1 } })
As you can see the roles taken is empty despite me adding markmodified and save(). I would like to know if I am missing something which is preventing me from saving the values in the schema.
Thanks in advance.
Here is how I push a comment to a thread in one of my apps using mongoose.
Thread.findByIdAndUpdate(body.thread, { $push: { comments: comment.id }})
I simply find the thread by the id, then use the $push operator to push the comment id to the comments attribute where I populate later.
You can read more into the $push operator here (mongoose v3.4) https://docs.mongodb.com/manual/reference/operator/update/push/

Resources