在Mongoose中使用Virtual返回查询的全名

Using a Virtual in Mongoose to return full name on a query

本文关键字:返回 查询 全名 Virtual Mongoose      更新时间:2023-09-26

我想用mongoose做一个查找查询,并得到返回的结果,其中包含用户的全名。现在,我有两个字段,firstName和lastName。当我查询数据库时,我希望mongoose将firstName和lastName连接起来,并返回一个名为fullName的字段。Mongoose有可能做到这一点吗?

另一种选择是查询数据库,获取结果,并循环遍历每个对象,并在循环的每次迭代中分配fullName。我觉得我有办法以某种方式利用猫鼬虚拟。

UserSchema
.virtual('name.full')
   .get(function () {
   return this.name.firstName + ' ' + this.name.lastName; 
});

示例查询:

User.find().exec()
.then(function(data){
    console.log(data);  //Should print out [{ _id: 123123232322, firstName:'john', lastName: 'Doe'}]
    //I would like it to print out: [{ _id: 123123232322, firstName:'john', lastName: 'Doe', fullName: 'John Doe'}]
});

通过将UserSchema上的toObject选项设置为{ getters: true }:,可以在console.log输出中显示虚拟

UserSchema.set('toObject', { getters: true });