【问题标题】:all mongoose queries stall所有 mongoose 查询都停止
【发布时间】:2018-05-15 00:50:34
【问题描述】:

从以前的答案来看,这可能与我的连接有关,但我似乎无法确定如何找到问题。我有几段看起来像这样的代码,结果是在调用任何模型函数后停止

connection - 服务器启动时打印成功

mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/test', { useMongoClient: true, promiseLibrary: require('bluebird') })
  .then(() =>  console.log('connection succesful'))
  .catch((err) => console.error(err));

model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var holdingsSchema = new Schema({
    pair: String,
    amount: Number
});

var holdingsModel = mongoose.model('holdingsModel', holdingsSchema);
module.exports = holdingsModel

和 api 端点

 holdingsModel.find(function(err, results) {
        if (err) {
            console.log('there is an error')
        }
        return res.json(results);
    }).then(results => console.log('the results: ' + results));
});

最后我收到一个 err: empty response。

【问题讨论】:

    标签: express mongoose


    【解决方案1】:

    find() 需要criteria object。第二个参数是回调。当你使用 Promise 时,你不需要回调。最后,您必须使用catch() 处理错误。

    holdingsModel.find({ pair: 'test' }).exec()
       .then(results => res.status(200).json(results))
       .catch(err => res.status(400).json(err));
    

    exec() 用于返回正确的承诺,如 here 所述。

    【讨论】:

    • 感谢您的关注。我尝试将 find 方法更新为您在此处拥有的方法,但仍然在客户端看到空响应。
    • 可能方向不正确,但我想知道是否有某种方法可以检查连接是否仍然有效?
    • @massphoenix 是的,你可以监听连接事件。请参阅this 文章。你需要mongoose.connection.on 的东西。当然,您还必须将{ pair: 'test' } 更改为正确的查询。 {} 返回该集合中的所有内容。
    • 谢谢@MikaS。我仍然不完全确定问题出在哪里,但我删除了我的 app.js 中包含 mongoose 这个词的所有内容,并按照那篇文章中的设置连接,让所有内容都启动并运行。
    猜你喜欢
    • 2017-03-27
    • 1970-01-01
    • 2021-03-03
    • 2015-07-04
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多