【问题标题】:How to get the data from mongoose query from one js file to another如何从一个js文件到另一个文件的mongoose查询中获取数据
【发布时间】:2018-06-21 17:58:11
【问题描述】:

我试图从 mongoose 查询中获取数据,该查询在另一个 js 文件中返回

我的代码:

config.js

module.exports = {
  FindinCol1: function() {
    console.log("Inside promise")
mongo.configuration.findOne({}).exec()
    .then(function(user){
   //   var result = [];
   console.log("user");
     resolve(user);
    })
    .then(undefined, function(err){
     console.log(err)
        })
     }
};

route.js

更新

     var siteconfig = require('./config');


      siteconfig.FindinCol1().then(function(items) {
  console.info('The promise was fulfilled with items!', items);
}, function(err) {
  console.error('The promise was rejected', err, err.stack);
});

我不知道自己犯了什么错误。

【问题讨论】:

  • 你得到的错误是什么?
  • 无法读取未定义的 then 的属性
  • 是否打印了任何控制台语句?
  • siteconfig.FindinCol1(function(items) { console.log(items); });我已经尝试过了,现在我没有收到错误,但是值在 config.js 中打印,但在 route.js 中没有
  • 在“mongo.configuration.findOne”之前添加一个返回

标签: node.js mongodb mongoose promise


【解决方案1】:

您看到的不是 Promise 的未定义解决方案,而是一个不返回任何内容的函数返回的未定义值。

你必须返回findOne({}).exec()创建的promise

module.exports = {
    FindinCol1: function() {
        console.log("Inside promise");
        // notice return...
        return mongo.configuration.findOne({}).exec()
        .then(function(user){
            console.log("user");
            return user;  // no need for "resolve" here, which looks undefined anyway
        })
        .catch(function(err){  // use catch for errors
            console.log(err);
        });
    }
};

【讨论】:

    猜你喜欢
    • 2018-11-13
    • 2017-06-13
    • 2020-09-25
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多