如何在 Express 项目中正确布局 Mongoose?

发布于 2024-12-04 19:13:02 字数 118 浏览 2 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

恰似旧人归 2024-12-11 19:13:02
// route.js
var mongoose = require("mongoose");

var Posts = mongoose.model("posts")
...

确保您设置了一个运行所有模型文件的引导机制。完成后,您应该为一组模型调用 mongoose.model("name", Model)

这已将这些模型缓存在猫鼬内部。所以你可以在任何你想要的地方调用 mongoose.model("name")

唯一重要的是执行顺序。模型&在运行路由之前需要注册模式。

这很简单:

// create app
var app = express.createServer(...);
// do stuff with app

var files = fs.readdirSync("models");
files.forEach(function(file) {
  require("models/" + file);
});

var routes = fs.readdirSync("routes");
routes.forEach(function(route) {
  require("routes/" + route)(app);
});

app.listen(80);

请注意,通常 readdirSync 是邪恶的,但在侦听服务器之前在启动时执行阻塞调用(如 require)是可以的

// route.js
var mongoose = require("mongoose");

var Posts = mongoose.model("posts")
...

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 :

// create app
var app = express.createServer(...);
// do stuff with app

var files = fs.readdirSync("models");
files.forEach(function(file) {
  require("models/" + file);
});

var routes = fs.readdirSync("routes");
routes.forEach(function(route) {
  require("routes/" + route)(app);
});

app.listen(80);

Note that normally readdirSync is evil but it's ok to execute blocking calls at startup time (like require) before your listen to your server

心舞飞扬 2024-12-11 19:13:02

当您 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文