如何在使用 findOne() 后从猫鼬/mongodb 文档中获取值



我正在制作一个民意调查应用程序,您可以在/createpoll 上填写新的问题和答案可能性。在索引页面上,您可以对投票进行投票。实时更新是使用Primus(websocket)完成的。

我使用的实时.js文件用作传递数据并触发事件的中心(例如,对投票进行投票,以便每个人都可以实时查看更新)。

当我连接到索引页面时,我想显示来自mongodb在线数据库集合的最新民意调查。我已经编写了查询并返回了一个文档。但是,我保存查询的变量在 console.log 或传递到我想将其放入 html 的索引页时返回未定义。

主要问题:如何将没有键的值存储到变量中?


我试图字符串化,解析,...但都带着错误回来。


// the connection works, uri details are at the top of the file, but I 
// won't include for safety. I can see the data getting stored.
mongoose.connect(uri, { useNewUrlParser: true})
.then((conn)=>{
let modelConn = conn.model ('poll', pollSchema);
let question = modelConn.findOne({},'question', {projection:{question:1, _id: 0}},function(err,obj) { console.log(obj); }).sort([['_id', -1]]);
let answer1 = modelConn.findOne({},'answer1', {projection:{answer1:1, _id: 0}}, function(err,obj) { console.log(obj); }).sort([['_id', -1]]);
let answer2 = modelConn.findOne({},'answer2', {projection:{answer2:1, _id: 0}}, function(err,obj) { console.log(obj); }).sort([['_id', -1]]);
primus.write({
"action": "showDbPoll",
"question": question,
"answer1": answer1,
"answer2": answer2
});

})
.catch((errorMessage) => {
console.log(errorMessage);
});
// console output from nodemon
{ question: 'a question' }
{ answer1: 'answer 1' }
{ answer2: 'answer 2' }

我希望将文档的值保存到变量中,以便可以将其传递到下一页。所以我的变量应该等于这个字符串:"一个问题">

从回调返回不起作用。您可以使用以下async..await

async function someFunc(uri) {
try {
const conn = await mongoose.connect(uri, { useNewUrlParser: true});
const modelConn = conn.model ('poll', pollSchema);
// not sure why you're using sort so skipped it
// maybe something like this ? https://stackoverflow.com/questions/13443069/mongoose-request-order-by
// .findOne({}, 'question', {sort: { _id: -1 }, projection:{ question:1, _id: 0 } });
const question = await modelConn.findOne({},'question', {projection:{question:1, _id: 0}});
const answer1 = await modelConn.findOne({},'answer1', {projection:{answer1:1, _id: 0}});
const answer2 = await modelConn.findOne({},'answer2', {projection:{answer2:1, _id: 0}});
primus.write({
"action": "showDbPoll",
"question": question,
"answer1": answer1,
"answer2": answer2
});
} catch (e) {
// handle error
console.error(e)
}
}
someFunc(uri)

无需向数据库发出 3 个请求,也可以避免投影和排序。试试这个代码:

mongoose.connect(uri, { useNewUrlParser: true})
.then(async (conn) => {
const modelConn = conn.model('poll', pollSchema);
const { question, answer1, answer2 } = await modelConn.findOne({});
primus.write({
"action": "showDbPoll",
"question": question,
"answer1": answer1,
"answer2": answer2
});
})
.catch((errorMessage) => {
console.log(errorMessage);
});

最新更新