gpt4 book ai didi

node.js - 正则表达式搜索错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:31 25 4
gpt4 key购买 nike

我对 mongo Node 和 Express 有点陌生,我遇到了一些问题。我正在尝试根据某些关键字查询数据库中的所有产品。理想情况下,我想找到一个包含用户搜索中的单词的产品,如果没有发现任何单词包含在集合中,则默认为固定产品

这是我的架构设置:

var  express  = require("express"),
mongoose = require("mongoose");

var productSchema = new mongoose.Schema({
name: String,
image: String,
description: String,
keywords: String,
});

module.exports = mongoose.model('产品', ProductSchema);

我的想法是根据用户的查询将用户与产品相匹配。即使他们输入完整的句子(目前仅适用于单个单词)。如果没有产品,我想默认为数据库中的一种产品。这是我的路线设置:

var express  = require("express"),
Product =require('../models/product'),
router = express.Router();

router.get('/myroute', function(req,res){
// if there's a query
if(req.query.search){
const regex = new RegExp(escapeRegex(req.query.search), 'gi');
var regexSearch = {
"keywords": {
"$regex": regex
}
};
Product.findOne(regexSearch, function(err, foundProduct){
if(err){
console.log('product not found');
} else{
res.render('show', {product: foundProduct});
}
});

} else{
Product.findOne({name: 'defaultP'}, function(err, foundProduct){
if(err){
console.log(err);
} else{
res.render('show', {product: foundProduct});
}
});

}

});

function escapeRegex(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

module.exports = router;

目前,当我搜索存在的关键字(但不是句子)时,一切正常。但是,如果我搜索数据库中不存在的句子或关键字,则会在渲染时收到错误:

Cannot read property 'name' of null at eval (eval at (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:524:12), :22:33) at returnedFn (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:555:17) at tryHandleCache (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:203:34) at View.exports.renderFile [as engine] (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:412:10) at View.render (/home/ubuntu/workspace/node_modules/express/lib/view.js:128:8) at tryRender (/home/ubuntu/workspace/node_modules/express/lib/application.js:640:10) at EventEmitter.render (/home/ubuntu/workspace/node_modules/express/lib/application.js:592:3) at ServerResponse.render (/home/ubuntu/workspace/node_modules/express/lib/response.js:971:7) at /home/ubuntu/workspace/routes/match.js:20:23 at Query. (/home/ubuntu/workspace/node_modules/mongoose/lib/model.js:3755:16) at /home/ubuntu/workspace/node_modules/mongoose/node_modules/kareem/index.js:277:21 at /home/ubuntu/workspace/node_modules/mongoose/node_modules/kareem/index.js:131:16 at nextTickCallbackWith0Args (node.js:436:9) at process._tickCallback (node.js:365:13)

最佳答案

尝试一下,然后将函数 escapeRegex 放入 RegExp 中。

var regExpr = new RegExp(".*" + req.query.search + ".*", "i");
var regexSearch = {
"keywords": regExpr
};

关于node.js - 正则表达式搜索错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44820667/

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