您当前的位置:首页 > 计算机 > 软件应用 > 数据库 > MongoDB

使用 Mongoose 连接到 MongoDB 数据库

时间:12-14来源:作者:点击数:

这 mongoose.connect() 函数是 使用 Mongoose 连接到 MongoDB ( mongoosejs 商业网/docs/connections.html)。连接后,您可以 创建一个 Mongoose 模型 ( mongoosejs 商业网/docs/models.html)并开始与 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() 函数返回一个 ( mongoosejs 商业网/docs/api/mongoose.html)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;

许多 较早的教程建议收听连接事件 ( theholmesoffice 商业网/mongoose-connection-best-practice/)。 这不是绝对必要的,因为 自行处理自动重新 ( thecodebarbarian 商业网/managing-connections-with-the-mongodb-node-driver.html)如果 Mongoose 在初始连接后失去与 MongoDB 的连接,mongoose.connect() 如果 Mongoose 最初连接到 MongoDB 时出现错误,则仅返回拒绝。 一旦 Mongoose 成功连接,如果它失去连接,它会自动处理重新连接。

这 reconnectFailed 事件

Mongoose 处理自动重新连接到 MongoDB。 在内部,底层 MongoDB 驱动程序尝试重新连接 reconnectTries 每一次 reconnectInterval 如果您连接到单个服务器,则为毫秒。 你可以设置 reconnectTries 和 reconnectInterval 在里面 mongoose.connect() 选项 ( mongoosejs 商业网/docs/api/mongoose.html)里面。

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 在初始连接后失去与副本集的连接,它将无限期地重新连接。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐