【问题标题】:How to get the value from a mongoose/mongodb document after using findOne()使用 findOne() 后如何从 mongoose/mongodb 文档中获取值
【发布时间】:2019-09-12 11:06:46
【问题描述】:

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

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

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

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


我尝试过字符串化、解析……但都返回错误。


// 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”

【问题讨论】:

    标签: javascript node.js express mongoose primus


    【解决方案1】:

    从回调返回将不起作用。你可以使用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)
    

    【讨论】:

    • 这行得通! :D 非常感谢!被这个任务卡住了 2 周!我使用排序的原因是从数据库中获取最新的民意调查。这样,如果人们浏览该网站,他们将看到最后的民意调查:)
    【解决方案2】:

    不需要对数据库进行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);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2016-07-18
      • 1970-01-01
      • 2014-04-30
      相关资源
      最近更新 更多