使用 Mongoose 连接到 MongoDB 数据库
这 mongoose.connect()
函数是 使用 Mongoose 连接到 MongoDB 。连接后,您可以 创建一个 Mongoose 模型 并开始与 MongoDB 交互。
// Connect to a MongoDB server running on 'localhost:27017' and use the
// 'test' database.
await mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true // Boilerplate for Mongoose 5.x
});
// Once you're connected to MongoDB, you can create a user model and
// use it to save a user to the database.
const userSchema = new mongoose.Schema({ name: String });
const UserModel = mongoose.model('User', userSchema);
await UserModel.create({ name: 'test' });
这 mongoose.connect()
函数返回一个 Promise,如果 Mongoose 无法连接则拒绝。
const options = { useNewUrlParser: true };
// Try to connect to `nota.domain`, which should fail
const err = await mongoose.connect('mongodb://nota.domain:27017/test', options).
catch(err => err);
// 'failed to connect to server [nota.domain:27017] on first connect'
err.message;
许多 较早的教程建议收听连接事件 。 这不是绝对必要的,因为 自行处理自动重新 如果 Mongoose 在初始连接后失去与 MongoDB 的连接,mongoose.connect()
如果 Mongoose 最初连接到 MongoDB 时出现错误,则仅返回拒绝。 一旦 Mongoose 成功连接,如果它失去连接,它会自动处理重新连接。
这 reconnectFailed
事件
Mongoose 处理自动重新连接到 MongoDB。 在内部,底层 MongoDB 驱动程序尝试重新连接 reconnectTries
每一次 reconnectInterval
如果您连接到单个服务器,则为毫秒。 你可以设置 reconnectTries
和 reconnectInterval
在里面 mongoose.connect()
选项 里面。
mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true, // Boilerplate
// If you lose connectivity, try reconnecting every 2 seconds. After 60
// attempts, give up and emit 'reconnectFailed'.
reconnectTries: 60,
reconnectInterval: 2000
})
当 Mongoose 放弃时,它会调用 connection 里面的的 reconnectFailed 事件。
// If Mongoose gave up trying to reconnect, kill the process.
mongoose.connection.on('reconnectFailed', () => {
process.nextTick(() => {
throw new Error('Mongoose could not reconnect to MongoDB server');
});
});
如果您连接到副本集, reconnectTries
和 reconnectInterval
不要做任何事情。 如果 Mongoose 在初始连接后失去与副本集的连接,它将无限期地重新连接。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论