检查猫鼬连接状态而无需创建新连接 [英] Check mongoose connection state without creating new connection

查看:88
本文介绍了检查猫鼬连接状态而无需创建新连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些测试-即超级测试-可以加载我的Express应用.这个程序创建一个猫鼬的连接.我想知道如何从测试中检查该连接的状态.

I have some tests - namely Supertest - that load my Express app. This app creates a Mongoose connection. I would like to know how to check the status of that connection from within my test.

在app.js中

mongoose.connect(...)

在test.js中

console.log(mongoose.connection.readyState);

如何访问app.js连接?如果我在test.js中使用相同的参数进行连接,将会创建新的连接还是寻找现有的连接?

How to access the app.js connection? If I connect using the same parameters in test.js will that create a new connection or look for existing one?

推荐答案

由于猫鼬模块导出了单例对象,因此您不必在test.js中进行连接即可检查连接状态:

Since the mongoose module exports a singleton object, you don't have to connect in your test.js to check the state of the connection:

// test.js
require('./app.js'); // which executes 'mongoose.connect()'

var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);

就绪状态为:

  • 0:已断开连接
  • 1:已连接
  • 2:连接
  • 3:断开连接

这篇关于检查猫鼬连接状态而无需创建新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆