Nodejs mongoose模糊查询一个实例
Nodejs mongoose模糊查询一个实例
不会弄图片,要不贴上案例效果就一目了然了。 mongoose模糊查询我现在的理解就是–验证规则(RegExp)。 只要能够匹配,则此行就返回值。 代码: 前端:var searchnotes = function(t,e){ //文章列表模糊查询, if(e.which == 13){ var $t = $(t); var params = {title:$(t).val()} $.ajax({ url:"/searchnotes", type:“post”, data: params, dataType: ‘json’, success: function(res){ if(res.status == 0){ var $div = $t.parent().parent(); $div.children(“li”).remove(); $div.children(".pull-left").remove();
for(i in res.notes){
$div.append('<div class="pull-left mr5 col_ff99">'+(parseInt(i)+1)+'.</div>');
var li = '<li id="'+res.notes[i]._id+'" class="none_outside" onclick="postnoteid(this);">';
li += '<h4 class="cur_point" style="margin-bottom:0;"><span class="pull-left rowlength600 hover1">'+res.notes[i].title +'</span>';
li +='<span class="pull-right fc07 mr25">'+res.date[i]+'</span><div class="clear"></div></h4>';
li += '<p class="w600">'+res.notes[i].content.showlength(300).blankString(4)+'</li>'
$div.append(li);
}
}else{
window.location.href = "/logout";
}
},
error: function (msg) {
if ( msg.statusText == 'timeout' ) alert('网络超时');
else $("#ss1").html("更新失败").show();;
}
});
}
}
后端: var Note = require("./…/moudels/notes.js"); app.post("/searchnotes",function(req,res){//利用post接收,用已做好的Note类的findRegx方法处理 Note.findRegx(req,res); });
//Note类 Notes.prototype.findRegx=function(req,res){ if(typeof req.session.name !=“undefined”){ Note.find({title:new RegExp(req.body.title),username:req.session.name},function(err,persons){// var arr = new Array(); for(i in persons){ arr[i] = persons[i].update.getFullYear()+"."+fo_mat(persons[i].update.getMonth()+1)+"."+fo_mat(persons[i].update.getDate())+" “ +(persons[i].update.getHours())+”:"+fo_mat(persons[i].update.getMinutes()); } res.send({status:0,notes:persons,date:arr}); }); } else{ res.send({status:1}); }
} module.exports = new Notes();
Node.js Mongoose 模糊查询实例
前端代码
前端部分使用 jQuery 发送 AJAX 请求来执行模糊查询。当用户按下回车键时,会触发查询操作。
var searchnotes = function(t, e) {
if (e.which == 13) {
var $t = $(t);
var params = { title: $(t).val() };
$.ajax({
url: "/searchnotes",
type: "POST",
data: params,
dataType: 'json',
success: function(res) {
if (res.status == 0) {
var $div = $t.parent().parent();
$div.children("li").remove();
$div.children(".pull-left").remove();
for (i in res.notes) {
$div.append('<div class="pull-left mr5 col_ff99">' + (parseInt(i) + 1) + '.</div>');
var li = '<li id="' + res.notes[i]._id + '" class="none_outside" onclick="postnoteid(this);">';
li += '<h4 class="cur_point" style="margin-bottom:0;"><span class="pull-left rowlength600 hover1">' + res.notes[i].title + '</span>';
li += '<span class="pull-right fc07 mr25">' + res.date[i] + '</span><div class="clear"></div></h4>';
li += '<p class="w600">' + res.notes[i].content.showlength(300).blankString(4) + '</li>';
$div.append(li);
}
} else {
window.location.href = "/logout";
}
},
error: function(msg) {
if (msg.statusText == 'timeout') alert('网络超时');
else $("#ss1").html("更新失败").show();
}
});
}
};
后端代码
后端使用 Express 和 Mongoose 来处理 POST 请求,并执行模糊查询。
// 引入模型
var Note = require("./models/notes.js");
// 设置路由
app.post("/searchnotes", function(req, res) {
Note.findRegx(req, res);
});
// 定义模型方法
const Notes = require("./models/notes.js");
Notes.prototype.findRegx = function(req, res) {
if (typeof req.session.name !== "undefined") {
Note.find(
{
title: new RegExp(req.body.title, "i"), // 使用正则表达式进行模糊查询
username: req.session.name
},
function(err, persons) {
if (err) {
console.error(err);
res.send({ status: 1 });
return;
}
var arr = [];
for (i in persons) {
arr.push(
persons[i].update.getFullYear() +
"." +
format(persons[i].update.getMonth() + 1) +
"." +
format(persons[i].update.getDate()) +
" " +
(persons[i].update.getHours()) +
":" +
format(persons[i].update.getMinutes())
);
}
res.send({ status: 0, notes: persons, date: arr });
}
);
} else {
res.send({ status: 1 });
}
};
// 实例化模型
module.exports = new Notes();
说明
- 前端:用户输入关键字后按回车键,通过 AJAX 请求向服务器发送查询请求。
- 后端:服务器接收到请求后,使用 Mongoose 的
find
方法结合正则表达式进行模糊查询。查询结果返回给前端,前端根据返回的数据动态生成 HTML 内容。
通过上述代码,你可以实现一个简单的 Node.js 应用中的模糊查询功能。
date可以在model中声明获取的格式的
之前用返回出来的值调用format,结果是此类型无该方法, 声明获取的格式,应该怎么写?
见api:
function dob (val) { if (!val) return val; return (val.getMonth() + 1) + “/” + val.getDate() + “/” + val.getFullYear(); }
// defining within the schema var s = new Schema({ born: { type: Date, get: dob })
// or by retreiving its SchemaType var s = new Schema({ born: Date }) s.path(‘born’).get(dob)
返回的就是一个格式化的日期了,如果确实需要的话
嗯,时间格式根据css样式调整的时候,需要格式化一下 在模型的对象设置了时间格式,牛逼,学习了。
针对你的需求,我们可以实现一个Node.js和Mongoose的模糊查询功能。以下是一个完整的例子,包括前端和后端的代码。
前端代码
前端代码负责收集用户输入并发送请求到后端进行模糊查询:
var searchnotes = function(t, e) {
if (e.which == 13) {
var $t = $(t);
var params = { title: $(t).val() };
$.ajax({
url: "/searchnotes",
type: "POST",
data: params,
dataType: 'json',
success: function(res) {
if (res.status == 0) {
var $div = $t.parent().parent();
$div.children("li").remove();
$div.children(".pull-left").remove();
for (var i = 0; i < res.notes.length; i++) {
$div.append('<div class="pull-left mr5 col_ff99">' + (i + 1) + '.</div>');
var li = '<li id="' + res.notes[i]._id + '" class="none_outside" onclick="postnoteid(this);">';
li += '<h4 class="cur_point" style="margin-bottom:0;"><span class="pull-left rowlength600 hover1">' + res.notes[i].title + '</span>';
li += '<span class="pull-right fc07 mr25">' + res.date[i] + '</span><div class="clear"></div></h4>';
li += '<p class="w600">' + res.notes[i].content.showlength(300).blankString(4) + '</p></li>';
$div.append(li);
}
} else {
window.location.href = "/logout";
}
},
error: function(msg) {
if (msg.statusText == 'timeout') alert('网络超时');
else $("#ss1").html("更新失败").show();
}
});
}
};
后端代码
后端代码负责处理请求,并使用Mongoose进行模糊查询:
const mongoose = require('mongoose');
const NoteSchema = new mongoose.Schema({
title: String,
content: String,
username: String,
update: Date
});
const Note = mongoose.model('Note', NoteSchema);
app.post("/searchnotes", function(req, res) {
if (typeof req.session.name !== "undefined") {
Note.find(
{ title: new RegExp(req.body.title, 'i'), username: req.session.name },
function(err, persons) {
if (err) return res.status(500).send(err);
var arr = [];
for (var i = 0; i < persons.length; i++) {
arr.push(persons[i].update.getFullYear() + "." +
format(persons[i].update.getMonth() + 1) + "." +
format(persons[i].update.getDate()) + " " +
persons[i].update.getHours() + ":" +
format(persons[i].update.getMinutes()));
}
res.send({ status: 0, notes: persons, date: arr });
}
);
} else {
res.send({ status: 1 });
}
});
注意事项
- RegExp构造函数:
new RegExp(req.body.title, 'i')
使用i
标志表示忽略大小写。 - 日期格式化:
format()
函数需要你自己定义,用于格式化日期字符串。 - 错误处理:确保添加适当的错误处理机制,以避免未处理的异常。
通过这种方式,你可以实现前端的输入与后端的模糊查询逻辑,从而获取匹配的结果。