NodeJS JavaScript and Mongo Communication



我在脚本标签下的 ejs 文件中放置了一个文本字段

var message = document.getElementById("typing").value;

我希望这个变量消息具有需要在数据库中搜索的关键字(mongodb(

我可以使用 NodeJs 文件与 db 连接并找到我想要的东西

dbo.collection('Leave').find({$text:{$search : " those "}},{projection:{_id: 0, What_are_those:1}}).toArray(function(err, result) {.......});

但我不习惯将其与 EJS 和 nodeJS 连接起来。基本上是两者之间的连接或绑定。

目前还不清楚您是如何发布数据的,但假设您将搜索页面发布到 URL"/search",请参阅下面的代码。

确保您的应用程序已连接到MongoDb。 创建可以向其提交搜索词的路由(首选 POST(。 路由使用猫鼬模型查询数据库,并将mongodb文档返回给ejs模板。

const mongoUrl = REPLACE_WITH_MONGOURL;
const mongoose = require('mongoose');
mongoose.connect(mongoUrl);
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB at: %s ', mongoUrl);
});
// assuming you post {"searchTerm": "SEARCH THIS STRING"} as body
app.post('/search', (req, res) => {
const searchTerm = req.body.searchTerm
model.find($text:{$search: searchTerm}).exec((err, doc) => {
res.render('path/to.ejs', { msg: doc });
});
});

EJS 应包含类似<%=msg.doc%>