【发布时间】:2021-06-01 14:14:55
【问题描述】:
我正在尝试这样做,以便如果我搜索一个名称,Mongodb 将搜索该文档,然后它将在 ejs 文件中显示它。它应该通过更改客户端js文件中H4字段的文本字段来做到这一点。但是当我尝试这样做时,它会一直说“查询”(这是从文档返回的搜索数据的名称)没有定义。但是,我只是在 mongodb 完成搜索并从查询中取回该数据后才尝试为 h4 命名。为此,我正在使用:Mongodb、express、EJS 和 nodejs。
Index.js:
router.post('/searchplayer', ensureAuthenticated, function(req, res){
const {text} = req.body;
var input = text
User.findOne({charactername: text})
.then(user => {
if(user) {
const { MongoClient } = require("mongodb");
const url = 'mongodb+srv://test:test1234@databasetest.5f9jh.mongodb.net/Databasetest?retryWrites=true&w=majority';
console.log('player found')
MongoClient.connect(url, function(error, db) {
if (error) throw error;
var dbo = db.db("Databasetest");
var query = { charactername: text };
dbo.collection("users").find(query).toArray(function(error, query, result) {
res.render('main', {
user: req.user,
query,
})
if (error) throw error;
console.log(result);
db.close();
})
});
} else {
console.log("Player does not exist")
}
})
})
一些澄清: 1:const 文本是人们在 ejs 文件中键入的值。 2:然后它开始在 mongodb 中进行搜索,以查看该名称是否出现在任何可用文档中,并返回该特定文档,如下所示: [{charactername: "Jordan"}] 我可以在控制台中看到记录。
但现在我正在尝试通过在 main.ejs 中使用此脚本来查看 ejs 中的这些数据:
//Search for user
document.getElementById('playersearchbtn').addEventListener('click',showotheruserpopup)
//Show other user if one is found
function showotheruserpopup() {
if (document.getElementById('searchplayerinput').value.length > 0) {
localStorage.setItem("otherusermenu","open")
document.getElementById('otheruserpopup').style.visibility = "Visible"
var userField = document.getElementById('otherusername')
userField.textContent = "<%= query%>"
localStorage.setItem('userField', userField.textContent)
var retrieveduserField = localStorage.getItem('userField')
userField.textContent = retrieveduserField
} else {
alert('You have to search something..')
}
}
//Close other user popup
document.getElementById('otheruserbtn').addEventListener('click',closeotheruserpopup)
function closeotheruserpopup() {
document.getElementById('otheruserpopup').style.visibility = "Hidden"
}
情况是,首先 otherusername textcontent 元素在开始时为空,但一旦在 mongodb 中完成此搜索,字段文本应更改为查询,即我从 mongodb 搜索返回的数据。但是当我尝试这个 EJS 时,它会一直告诉我在 userField.textContent 的脚本中没有定义查询。我觉得这很奇怪,因为即使这样也只能由脚本触发,但 EJS 会自动说它没有定义。但是我不知道如何定义,因为它只有在进行实际搜索后才会存在。
我该如何解决这个问题?
【问题讨论】: