I'm trying to rename the return of some of my variables using project after a find, but it doesn't work, like this:
#Vars: email, age, name
this.userModel.find(usersFilterQuery).project({age: 'ageUser'});
Is it just possible? Or just using aggregate?
CodePudding user response:
you can create a new object after geting the model
const user = this.userModel.find(usersFilterQuery).lean();
then you can use user propreties to create your new object
const newObject = {
prop1: user.email,
prop2: user.age,
prop3: user.name
}
then
return newObject;
CodePudding user response:
Yeah, this is not possible in find()
query. So, you should use the aggregate query if you want MongoDB to do this for you:
this.userModel.aggregate([
{
$match: usersFilterQuery
},
{
$project: {
age: '$ageUser'
}
}
]);
There is more thing that you can do. You can set virtual property in your Schema model, and Mongoose will create these for you on the fly (they will not be stored in the database). So, you will tell Mongoose to add age
property to each document that would be equal to the existing ageUser
property.
You can check more in the official docs.