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
  • 84,767
  • 185
  • 495
  • 805

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
  • 142,938
  • 30
  • 279
  • 274
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”);