I'd like to run a regex to achieve a "LIKE" type functionality on a virtual field in my User schema.
The following statement works for all of the fields 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);
});
The virtual field declaration in the mongoose schema for User
//full name
UserSchema.virtual('fullName')
.get(function() {
return this.firstName + ' ' + this.lastName;
});
What is the right approach to get the fullName field regex to work properly?
As you already stated (and showed us), fullName
is a virtual, it's on the application layer. You cannot query it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.