1

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? 
NeNaD
  • 18,172
  • 8
  • 47
  • 89
Robert
  • 63
  • 6
  • This question is a possible duplicate of: [How do I rename fields when performing search/projection in MongoDB?](https://stackoverflow.com/questions/23784370/how-do-i-rename-fields-when-performing-search-projection-in-mongodb) – smtaha512 Dec 21 '22 at 00:11
  • No, I saw this post, but it is using aggregate. Sorry if you can't help me. – Robert Dec 21 '22 at 00:18

1 Answers1

0

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.

NeNaD
  • 18,172
  • 8
  • 47
  • 89