在Mongoose中执行find()时调用虚拟方法

3

我已经在Mongoose Schema中创建了一个类似于这样的虚拟方法:

UserSchema.virtual('fullName').get(function() {
return this.firstName + ' ' + this.lastName;
}).set(function(replacedName) {
this.set(this.firstName, replacedName);
});

在服务器上执行find()方法:

User.find({}).exec(function(error, users) {
// I want to use virtual method for users array
users.set('fullName', 'Name will be replaced');
});

我能在不使用循环的情况下为数组使用虚拟方法吗? 我正在使用NodeJS和Mongoose。


1
我认为不行,因为Mongoose Schema只适用于单个对象,而不是数组对象。 - undefined
1个回答

3

正如评论中@truonghm所说,没有办法将虚拟方法一次性应用于文档数组。

您可以这样做:


循环

User.find({}).exec(function(error, users) {
   // Loop on results and execute the 'set' virtual method
   users.forEach(x => x.set('fullName', 'Name will be replaced'));
});

在架构中创建一个方法,它将为您完成任务:

查看 mongoose 文档中的查询助手部分

这将导致:

User.getAllOverrideName(fullName)
  .exec(function(error, users) {

  });

1
感谢您关于Mongoose中Query Helper部分的建议。我以前从未了解过这一点。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接