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

How to get the value from a mongoose/mongodb document after using findOne()

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

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

当我连接到索引页面时,我想显示来自 mongodb 在线数据库集合的最新民意调查。我已经编写了查询并返回了一个文档。但是,我在 returns 中保存查询的变量在 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"

回调返回无效。您可以像这样使用 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 ? 
    // .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);
});