node.js - 我应该在每个模型保存后关闭 Mongoose 连接吗?

标签 node.js mongodb express mongoose

我正在使用 Mongoose 来管理我的数据库架构。我将我的模型保存在我的应用程序的几个地方。我想知道我是否应该分别在每次查询之前和之后手动关闭并重新打开连接?我不确定对性能的影响。

例如在这个 createUser() ,数据库连接到,保存模型,然后关闭连接。每次createUser()都会发生这种情况叫做。

function createUser() {
    mongoose.connect(process.env.DB_PATH, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    const db = mongoose.connection
    db.once("open", function () {
        const userSchema = new mongoose.Schema({
            name: String,
        })
        const UserModel = mongoose.model("User", userSchema)
        const user = new UserModel({
            name: "John",
        })
        user.save().then(() => {
            mongoose.connection.close()
        })
    })
}

或者在应用程序的入口点保持连接处于事件状态并在应用程序终止时关闭它是否更好?

// server.js

mongoose.connect(process.env.DB_PATH, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})

// ...

process.on('SIGINT', () => {
    mongoose.connection.close(() => {
          process.exit(0);
      });
});


我也很想知道,如果使用另一个数据库驱动程序,比如 MySQL,策略会改变吗?

最佳答案

根据本书Mongoose For Application Development

the general best practice is to open your connection at application start up, and keep it open. However, there are times when you will want to close the connection. For example, if your application is shutting down, or restarting, the database connection needs to be manually closed, or if you are running a single-hit script rather than a persistent application.



好读选项 参加 mongoosejs关于您可以在连接字符串中设置的一些选项的文档。

并检查 best practice to connect to db也。

根据 Mongoose 文件:

autoReconnect - The underlying MongoDB driver will automatically try to reconnect when it loses connection to MongoDB. Unless you are an extremely advanced user that wants to manage their own connection pool



据我所知,这种问题取决于您的项目规模。

阅读完所有引用资料后,您将为您的项目找到商品。

关于node.js - 我应该在每个模型保存后关闭 Mongoose 连接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61601071/

相关文章:

javascript - Node.js 异步等待 - 错误 regeneratorRuntime

node.js - 如何以编程方式调用 yeoman 生成器?

javascript - 使用带有 Promise 的 ldapjs

javascript - 无法处理 React ApolloClient 中的错误

node.js - Mongoose 更新多个条件并回退

mongodb - 更改 MongoDB Compass 上的报告样本大小

mongodb - spring-data-mongodb 相当于 jackson 中的@JsonUnwrapped

javascript - 消息: 'Cast to number failed for value "undefined"at path in nodejs mongoose express

javascript - postman 中处理 express 发回的错误

node.js - axios response.data 奇怪的字符