0

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

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

当我连接到索引页面时,我想显示来自 mongodb 在线数据库集合的最新民意调查。我已经编写了查询并返回了一个文档。但是,我保存查询的变量在 console.logged 或传递到我想将其放入 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' }


我希望将文档的值保存到变量中,以便将其传递到下一页。所以我的变量应该等于这个字符串:“a question”

4

2 回答 2

0

从回调返回将不起作用。你可以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)
于 2019-04-23T10:44:34.760 回答
0

不需要向数据库发出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);
});
于 2019-04-23T10:53:18.157 回答