如何在 Express 项目中正确布局 Mongoose?
我在 models/mymodel.js
文件中创建了我的Schema
。我的模型和方法也都在里面。
如何将它们导出到我的路线
中?
I created my Schema
's in my models/mymodel.js
file. I also have my models in there as well as my methods.
How do I export them into my routes
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保您设置了一个运行所有模型文件的引导机制。完成后,您应该为一组模型调用
mongoose.model("name", Model)
。这已将这些模型缓存在猫鼬内部。所以你可以在任何你想要的地方调用
mongoose.model("name")
。唯一重要的是执行顺序。模型&在运行路由之前需要注册模式。
这很简单:
请注意,通常
readdirSync
是邪恶的,但在侦听服务器之前在启动时执行阻塞调用(如require
)是可以的Ensure that you set up a bootstrap mechanism that runs all your model files. Once that is done you should have called
mongoose.model("name", Model)
for a set of models.This has cached those models in mongoose internally. So you can just call
mongoose.model("name")
anywhere you want.The only thing that's important is order of execution. The model & schemas need to be registered before you run your routes.
This is as a simple as :
Note that normally
readdirSync
is evil but it's ok to execute blocking calls at startup time (likerequire
) before your listen to your server当您
require()
时,Mongoose 会创建一个单例,并且后续调用会返回相同的实例。因此,只要您在应用程序初始化时需要 mongoose,然后定义您的模型,它们就可以在您需要 mongoose 的任何其他文件中使用,如 Raynos 所描述的那样。
除非您想手动管理与数据库服务器的连接,否则最好在应用程序 init 中调用
mongoose.connect('...')
;连接将在请求之间持续存在。Mongoose creates a singleton when you
require()
it, and subsequent calls return the same instance.So as long as you require mongoose when your app inits, then define your models, they will be available in any other file where you require mongoose as described by Raynos.
Unless you want to manage connections to the db server manually, it's also a good idea to call
mongoose.connect('...')
in your app init; the connection will persist across requests.