1

I wonder where should my mongoose models go in the context of an ExpressJS application? I dont want to put everything into server.js/coffee. Is there an example somewhere?

Jiew Meng
  • 81,093
  • 172
  • 469
  • 784

3 Answers3

1

Put them in a directory called app/models and structure your application like this answer: ExpressJS How to structure an application?

Community
  • 1
  • 1
Peter Lyons
  • 137,901
  • 29
  • 269
  • 269
0

I create a data/models.js module which exports the various models I'm working with. For example models.js:

var mongoose = require("mongoose");
mongoose.connect("localhost", "databaseName");

var userSchema = mongoose.Schema({
  name: "string",
  email: "string",
  password: "string"
});

exports.User = mongoose.model("User", userSchema);

That allows me to require models elsewhere in the app like this:

var mongoose = require("mongoose")
  , User = require("../data/models").User
0

It should be following : models.js: module.exports = mongoose.model(“User”, userSchema);

Server.js: Const User = require(“../data/models”);

eldorcodes
  • 31
  • 2