【问题标题】:How can I extract the result of mongoose call and pass it into a variable如何提取猫鼬调用的结果并将其传递给变量
【发布时间】:2016-04-02 03:13:57
【问题描述】:

我尝试通过将它变成一个函数并通过返回来将其取出,但没有这样做。

我看到一个例子,有人使用module.exports.VariableName = objects;

我的问题是我仍然无法访问或使用该变量名。例如var names = Collection; 在同一个文件上。

ReferenceError: 集合未定义

我做错了什么?谢谢。

mongoose.connection.on('open', function(ref) {
  console.log('Connected to mongo server.');
  //trying to get collection names
  mongoose.connection.db.listCollections().toArray(function(err, names) {
    if (err) {
      console.log(err);
    } else {
      module.exports.Collection = names;
    }
  });
});

【问题讨论】:

  • 如果这个文件的requirelistCollections运行之前运行,那么它就没有Collection

标签: javascript node.js express mongoose


【解决方案1】:

问题是您将异步操作的结果分配给module.exports。这意味着您很可能在 使用 require() 访问它之后分配此数据。

通过仅考虑提供的代码,解决此问题的一种方法是将您的代码包装到使用 names 解析的 Promise 中:

module.exports = function(mongoose) {
  return new Promise(function(resolve, reject) {

    mongoose.connection.on('open', function (ref) {
      console.log('Connected to mongo server.');
      //trying to get collection names
      mongoose.connection.db.listCollections().toArray(function(err, names) {
        if (err) {
          reject(err);
        }
        else {
          resolve(names);
        }
      });
    });
  });
}

然后像这样使用它:

require('PATH_TO_CODE_ABOVE')(mongoose).then(function(collection) {
  console.log(collection); // This logs the names collection
}, function(err) {
  console.log(err); // this will log an error, if it happens
});

【讨论】:

    猜你喜欢
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多