简体   繁体   English

猫鼬找到要重命名的项目

[英]Mongoose find with project to rename

I'm trying to rename the return of some of my variables using project after a find, but it doesn't work, like this:我试图在查找后使用 project 重命名我的一些变量的返回值,但它不起作用,如下所示:

#Vars: email, age, name #Vars:电子邮件、年龄、姓名

    this.userModel.find(usersFilterQuery).project({age: 'ageUser'});

 Is it just possible? Or just using aggregate? 

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;

Yeah, this is not possible in find() query.是的,这在find()查询中是不可能的。 So, you should use the aggregate query if you want MongoDB to do this for you:因此,如果您希望 MongoDB 为您执行此操作,则应使用聚合查询:

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).您可以在 Schema 模型中设置虚拟属性,Mongoose 会即时为您创建这些属性(它们不会存储在数据库中)。 So, you will tell Mongoose to add age property to each document that would be equal to the existing ageUser property.因此,您将告诉 Mongoose 向每个文档添加age属性,该属性等于现有的ageUser属性。

You can check more in the official docs .您可以在官方文档中查看更多内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM