I'm trying to get the users from the mongo database using mongoose.
If i select a user i want to eliminate that user records and get all the remaining users from database.
how can i do that?
you can try to use the query below:-
UsersModel.find({ email: { $ne: 'testemail#email.com' } })
Let me know if it helps. Thanks
Here User is the user model. we will get all users except the current user
const users = User.find({ _id: { $ne: user._id } })
UsersModel.find({ email: { $ne: 'testemail#email.com' } })
for more follow this url
https://docs.mongodb.com/manual/reference/operator/query/ne/
Well, if you want to exclude just one user, you can use
db.collection.find( { name: { $ne: "name" } } )
And if you want to exclude more than one records. May be more than one selected records. This is the way to go
db.collection.find( { name: { $nin: ["name1", "name22"] } } )
Related
My aim is to hit api endpoint and only pass one query variable and try to filter out any of the columns based on single variable.
I have multiple users in database like:
{
id: 1,
email: 'test+1#test.com',
username: 'test',
phone_number: '+651231231',
skillsets: 'Drawing, cooking',
hobby: 'Sleeping',
},
{
id: 2,
email: 'test+2#test.com',
username: 'test 2',
phone_number: '+6512312311231',
skillsets: 'Drawing, cooking',
hobby: 'Drawing',
}
My function/Query
let users = this.repo.createQueryBuilder('user');
if (query && query !== '') {
users = users
.where('user.email like :email', { email: `%${query}%` })
.orWhere('user.username like :username', {
username: `%${query}%`,
})
.orWhere('user.phone_number like :phone_number', {
phone_number: `%${query}%`,
})
.orWhere('user.skillsets like :skillsets', {
phone_number: `%${query}%`,
})
.orWhere('user.hobby like :hobby', { hobby: `%${query}%` });
}
return users.getMany();
My api endpoint would be something like
/api/users?query=Sleeping
I can't filter by anything else other than email and I assumed is because of initial where but I am not entirely sure how to cater for this scenario.
I appreciate if anyone can point me to the right direction.
I was looking to implement something similar and I found the answer in another Stackoverflow Question
It is possible to use OR clause using the simple typeorm .find() options as described in TypeORM docs.
To query with OR operator you'll need to use an array of conditions instead of an object.
let users = await user.find({
where: [
{ email: Like(%${query}%) },
{ skillsets: Like(%${query}%) },
{ username: Like(%${query}%) }
]
});
You can try something like this. Just add the other columns.
users = users
.where('user.email like :query AND (user.username like :query OR user.phone_number like :query)', { query: `%${query}%` })
You can use setParameter function from the query builder, and use the value wherever you pass the key of the parameter.
So maybe you can improve your code like this:
const users = this.repo.createQueryBuilder('user');
if (query) {
users
.where('user.email LIKE :query')
.orWhere('user.username LIKE :query')
.orWhere('user.phone_number LIKE :query')
.orWhere('user.skillsets LIKE :query')
.orWhere('user.hobby LIKE :query')
.setParameter('query', `%${query}%`);
}
return users.getMany();
Hope this helps.
I am trying to build a social network. I have a collection of "connections"/"friend requests".
the schema is as follows:
{
senderId: { type: String },
receiverId: { type: String },
approved: { type: Boolean },
},
when the person didn't approve the connection yet, the connection is marked with "pending".
when the user enter to the website, i get all the pending connections people sent him, with this command:
const requestsPending = await Connection.find({
receiverId: userId,
approved: false,
});
the thing is, in the backend, I want to get the details of the people who send the friend requests (so I can show their name+picture).
I want to loop over the pending requests array, and get the extra data of the user who sent the request.
await User.findById(requestsPending[0][senderId]);
any idea how to do it for each element? what's the best approach?
or any idea how to do it more efficiently?
thank you.
this seems to work:
var requestsPendingWithUsersData = await Promise.all(
requestsPending.map(async (item) => {
const userData = await User.findById(item.senderId);
return {
item,
senderData: { picture: userData.picture, name: userData.username },
};
})
);
await User.find({
'senderId': { $in: [
101,102,103,...
]}
})
You can try something like the above, where you pass an array of senderID to $in. The $in clause is similar to like operator in SQL.
If the senderId is an ObjectId, pass them as ObjectID types
await User.find({
'senderId': { $in: [
mongoose.Types.ObjectId(<senderID>),
]}
})
If the mongo Document is heavier/larger, use lean() at the end of the query. Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document.
await User.find({
'senderId': { $in: [
101,102,103,...
]}
}).lean()
i have a collection for users transactions. i want to use a query by three id of users to get last transaction for each one. and i don't want to use a loop to do a query per user.
i used this:
const items = await db
.collection("transactions")
.find({ user: users[1] , user: users[2], user: users[3] })
.limit(3)
.sort({ $natural: -1 })
.toArray();
but it doesn't contain one result per condition because i know i'm doing it wrong.
i use:
const MongoClient = require("mongodb").MongoClient;
how should i do that?
thanks.
You probably need to do an aggregation using $group and $last.
https://docs.mongodb.com/manual/reference/operator/aggregation/group/#examples
db.collection("transactions").aggregate( [
{
$group: {
_id: user,
txnId: { $last: "$_id" }
}
}
] ).toArray();
This answer might also help you: https://stackoverflow.com/a/32134655/1742298
this is my question.js and user.js schema model with mongoose as below, could anyone help how to populate all the username lists in array object of likes:[] with Node js because I was facing this problem almost 2 weeks now, I could not populate the username from a user inside likes. Please, I appreciate your suggestion.
question schema model
user schema model
To populate user details, Please use
Post.findOne( { _id: id } )
.populate( "user" )
.populate( "likes.user" );
To get liked post, please use
Post.find({ "likes": { "$gt": 0 } }, function(err, data) {
})
or using where, here may get error if likes fields is missing or empty, so please check if it is exists
Post.find( {$where:'this.likes.length>0'} )
so please use where and exists
Post.find( {likes: {$exists:true}, $where:'this.likes.length>0'} )
I tried your code and got it working using your model. If you are using user only you can directly call .populate("user") but if its nested you need to do .populate("likes.user")
Post.findOne( { _id: id } ).populate( "user" ).populate( "likes.user" );
Yes, thank you to Ratnadeep Bhattacharyya, now I able to populate username in likes array object and also able to return the only a specific array of likes. Below is the working code:
Happy Coding, Jonh
//#route api/post/get/likes
router.get('/get/likes/:postId', auth, async (req, res) => {
try {
//check if post exist
const likes = await Post.findOne({ _id: req.params.postId })
.populate('user', ['name'])
.populate('likes.user', ['name']);
return res.status(200).json(likes.likes);
} catch (error) {
console.log(error.message);
res.status(500).json({ msg: 'Server error' });
}
});
I have this query ( mongoose)
user = {email:'my#email.com};
return this.company.get().findOne({
name: companyName,
users: { $elemMatch: user }
}).then((res: ICompany) => {
console.log(res.users);
}
The query is working.
The problem is that I was expecting one user in res.users (the one that match the $elemMatch), instead it returns all the users and to select my User I have to do a for-loop over all the users.
Is it possible to modify my query in the way that the res.users is populated with the user that match the email?
Thank you
Use of projection, here the documentation of mongodb 3.6
return this.company.get().findOne({
name: companyName,
users: { $elemMatch: user }
}, {
'users.$': 1,
}).then((res: ICompany) => {
console.log(res.users);
});