gpt4 book ai didi

node.js - 我应该需要 mongoose 模型还是直接从 mongoose 获取

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:09 25 4
gpt4 key购买 nike

我的文件 models/Model.js 中有一个模型,如下所示:

const mongoose = require('mongoose')
const modelSchema = mongoose.Schema({ name: String })
const Model = mongoose.model('Model', modelSchema)
module.exports = Model

然后,当我使用它时,我会像任何其他模块一样导入它:

const Model = require('../models/Model')

我的问题是:如果每次我require一个模块时都会执行代码(在这种情况下,每次导入它时它都会“运行”Model.js),这样导入它会更有效(或者至少更有意义)吗?:

const mongoose = require('mongoose')
const Model = mongoose.model('Model')

最佳答案

您的问题包含错误的假设:

If every time I require a module the code is executed (in this case it would "run" Model.js every time I import it)...

Model.js 中的代码仅在第一次调用 require 来加载该模块时运行。然后将生成的模块对象放置在 require.cache 中对同一模块的后续 require 调用只是从缓存中返回相同的模块对象。

因此,这两种方法之间没有明显的性能差异,这取决于您的个人喜好。

关于node.js - 我应该需要 mongoose 模型还是直接从 mongoose 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46345927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com