node.js - 虚拟字段上的 Mongoose 正则表达式

标签 node.js mongodb mongoose

我想运行正则表达式以在我的用户架构中的虚拟字段上实现“LIKE”类型的功能。

以下语句适用于所有字段except *fullName*

var searchString = stringUtils.removeMultipleSpaces(stringUtils.stripSpecialCharacters(req.param('searchString')));
        var regex = new RegExp(searchString);
        var query = User.find().or([{ 'firstName' : { $regex: regex}}, { 'lastName': { $regex: regex }},
            { 'userName': { $regex: regex }}, { 'fullName' : {$regex: regex }}]).sort('lastName');
        query.select('firstName lastName userName fullName');
        query.exec(function(err, users) {
            res.send(users);
        });

User 的 mongoose 模式中的虚拟字段声明

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

使全名字段正则表达式正常工作的正确方法是什么?

最佳答案

正如您已经说过(并向我们展示的),fullName 是一个虚拟的,它位于应用程序层。你不能查询它。

另请参阅:Sorting by virtual field in mongoDB (mongoose)

关于node.js - 虚拟字段上的 Mongoose 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16944842/

相关文章:

mongodb - 通过浏览他/她的所有帖子获得该用户收到的喜欢总数 MongoDB

mongodb - 将日期转换为时间戳 mongodb

node.js - Azure Web 聊天测试显示 "There was an error sending this message to your bot: HTTP status code Unauthorized"

javascript - 在 react 应用程序中简单连接到 mongodb

javascript - 新的:true option returns me the old value in MongoDB

node.js - Mongoose 用 $or 条件更新文档

node.js - 如何在 Node.js 中检查 MongoDB 连接是否处于事件状态

Javascript Websocket Close = 服务器崩溃

android - 如何使用云功能向具有 FCM token 的多个设备发送推送通知

javascript - 如何在nodejsexpress中处理response和next