Split users ids for database query [duplicate] - node.js

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

Related

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

Delay when removing row in postgres with knex

I have a local postgres database running on my machine. I use node.js to access it. I have a table called 'friends' where every row is a user and a friend. I also have a table called 'users' where every row has all basic info about a user(e.g name and such).
When I want to remove a friendship between two users I have to remove two rows from the 'friends' table. I do this with this function:
const removeFriend = async (clientId, friendId) => {
// initiate transaction
return db
.transaction((trx) => {
// remove friendship from client
trx('friends')
.where({ user_id: clientId, friend_id: friendId })
.del()
.then(() => {
// remove friendship from friend
return trx('friends').where({ user_id: friendId, friend_id: clientId }).del();
})
// if all good then commit
.then(trx.commit)
// if bad then rollback
.catch(trx.rollback);
})
.catch(() => 'error');
};
I call the removeFriend function this way removeFriend(clientId, friendId)
Then when i want to get a list of all friends with their names from the database i use this function:
const getUserFriends = async (clientId) => {
// get friends
return db('friends')
.where({ user_id: clientId })
.join('users', 'users.id', 'friends.friend_id')
.select('friends.friend_id', 'users.name')
.then((friends) => friends)
.catch(() => 'error');
};
I call the getUserFriends function this way await getUserFriends(clientId)
The problem is that when I use removeFriend function and then directly use the getUserFriends function i get a list where the users are still friends. However, If i look in the database the rows have been deleted so naturaly i should get a list where the users are not friends. Do I use the await wrong or something?

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!

Mongoose find - use returned data and add to it in a variable [duplicate]

This question already has answers here:
How do you turn a Mongoose document into a plain object?
(9 answers)
Closed 4 years ago.
Using Express and Mongoose I have the below code which finds a user, checks the username then matches the password.
/* POST signin with user credentials. */
router.post('/signin', async (req, res, next) => {
let result = await User.find({
email: req.body.email
});
let user = result[0];
bcrypt.compare(req.body.password, result[0].password, (err, result) => {
if (result) {
user._doc.token = jwt.sign({
email: req.body.email
}, config.secret, {
expiresIn: 86400,
});
res.send(user);
} else {
res.status(401).send({
message: 'Password does not match.'
});
}
});
});
When the JWT token is signed I want to add the token key val to the user object and return it.
But after lots of trial and error I was unable to do user.token =jwt.sign and I have to do user._doc.token = jwt.sign.
Being new to Mongoose and MongoDB, is this the only way I can add to a returned document that I want to assign to a variable to and make it mutable?
Try using .toObject() on your user document to get a plain javascript object, in which you can operate as you like.
The code
let user = result[0].toObject();
should return you the plain user object, then you can make user.token = jwt.sign.
For reference, see http://mongoosejs.com/docs/api.html#document_Document-toObject

Resources