gpt4 book ai didi

javascript - 如果使用特殊字符存储值,则使用 $regex 的 Mongoose 查找不会返回预期结果

转载 作者:可可西里 更新时间:2023-11-01 10:46:22 26 4
gpt4 key购买 nike

我正在尝试构建一个搜索用户名或全名的搜索功能......它工作正常但如果用户名像这样“example.name”或“example_name”如果我这样搜索它没有返回结果“examplename"或 "example name"如何解决这个问题以返回匹配的字符,即使是特殊字符

用户架构

const mongoose = require("mongoose");
const bcrypt = require("bcrypt-node");
const uniqueValidator = require("mongoose-unique-validator");
const schemaTypes = mongoose.Schema.Types;
const userSchema = new mongoose.Schema(
{
firstName: { type: String, required: true, trim: true },
lastName: { type: String, trim: true },
fullName: {type: String, trim: true},
username: { type: String, trim: true, unique: true, lowercase: true },
email: {
type: String,
unique: true,
trim: true,
lowercase: true,
required: true
},
password: { type: String, select: false },
gender: { type: String, default: "male" },
birthDate: Number,
location: { type: [Number], index: '2d' }, // [<longitude>, <latitude>]
bio: {type: String, default: ""},
profilePhoto: {type: String, default: "default-user-profile.jpg"},
private: { type: Boolean, default: false },
favouriteUsers: [{ type: schemaTypes.ObjectId, ref: "users" }],
blockedUsers: [{ type: schemaTypes.ObjectId, ref: "users" }],
tempPassword: String,
tempToken: String,
socialId: String,
favouriteRequests: [{ type: schemaTypes.ObjectId, ref: "users" }],
requests: [{ type: schemaTypes.ObjectId, ref: "users" }],
followers: [{ type: schemaTypes.ObjectId, ref: "users" }],
following: [{ type: schemaTypes.ObjectId, ref: "users" }],
playerId: {type: [String], default: []}
},
{ timestamps: true }
);
userSchema.plugin(uniqueValidator, { message: "This {VALUE} is used" });
userSchema.index({ "$**": "text" });
userSchema.pre("save", function(next) {
const user = this;
if (!user.isModified("password")) return next();
if (user.password) {
bcrypt.hash(user.password, null, null, function(err, hashedPassword) {
if (err) {
return;
}
user.password = hashedPassword;
next();
});
}
});

userSchema.pre("save", function(next) {
const user = this;
if (!user.isModified("firstName") && !user.isModified("lastName")) return
next();
if (user.firstName || user.lastName) {
user.fullName = user.firstName + " " + user.lastName;
next();
}
});
userSchema.methods.comparePassword = function(password) {
return bcrypt.compareSync(password, this.password);
};

module.exports = mongoose.model("users", userSchema);

代码

function search(keyword){
return new Promise((resolve,reject) => {
const User = require('../models/users');
let str = keyword.replace(/[`~!#$%^&*()|+\=?;:'",<>\{\}\[\]\\\/]/gi, "");
let key = new RegExp(str, "ig");
User.find({
$or: [
{ fullName: { $regex: key } },
{ username: { $regex: key } },
{ firstName: { $regex: key } },
{ lastName: { $regex: key } },
{ email: { $regex: key } }
]
}).exec(async (err, users) => {
if(err) return reject(err);
resolve(users);
})
})
}

示例 1

如果关键字输入“ahmed ibrahim”或“ahmed.ibrahim”结果符合预期

示例 1 的结果

[
{
"_id": "5b40d19ae4fc082ca8f2ff3b",
"profilePhoto": "http://localhost/public/male-image.jpg",
"firstName": "Ahmed",
"lastName": "Ibrahim",
"username": "ahmed.ibrahim65356",
"email": "example@gmail.com",
"fullName": "Ahmed Ibrahim"
}
]

例2问题

如果关键字是“ahmedibrahim”

我预计之前的结果 put 不会返回任何空数组 [] hot to solve this or any suggestions match characters even contain special characters

最佳答案

它基本上不起作用,因为您正在搜索“ahmedibrahim”并且它无法与文档中的任何字段相关联。

所以对于这个特定的场景,我要做的是创建一个新字段说“concatFullName”,它应该保存为 firstname+lastname,然后在你的查找中使用该字段 contactFullName。

contactFullName : { $regex: 键 }

尝试下面的聚合示例,

db.getCollection('test').aggregate({
$project: {
docs: "$$ROOT",
concatname: {
$concat: [
'$firstName',
'$lastName',
]
}
}
}, {
$match: {
concatname: {
$regex: "^ahmedIbrahim$",
$options: "i"
},
}
}, {
$group: {
_id: "$_id",
docs: {
$push: "$docs"
}
}
});

关于javascript - 如果使用特殊字符存储值,则使用 $regex 的 Mongoose 查找不会返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51481467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com