使用findOne()

时间:2019-04-23 09:33:08

标签: javascript node.js express mongoose primus

我正在制作一个民意调查应用程序,您可以在/ createpoll上填写一个新的问题并回答可能性。在索引页面上,您可以对民意调查投票。实时更新使用Primus(网络套接字)完成。

我使用的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' }


我希望将文档的值保存到变量中,以便将其传递到下一页。因此,我的变量应等于以下字符串:“一个问题”

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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);
});