David David - 4 months ago 27
Javascript Question

Referencing Sequelize Model in Controller in Node.js

I am having an issue which I just can't seem to wrap my head around.

I have created a model call Users. It is in the models folder and called Users.js

module.exports = function(sequelize, DataTypes) {
var Users = sequelize.define("Users", {
firstName: DataTypes.STRING,
surname: DataTypes.STRING
return Users;

The table creates in postgresql exactly how I imagine.

Now, the way I understand how it should work is that in the controller I can call a create method which would insert rows into this table. In this case I have a controller called home.js which looks as follows:

Users.sync({force: true}).then(function () {
return Users.create({
firstName: "David",
surname: "Meek"

However I just get errors saying Users cannot be found. Which makes sense, I can't recall any place where I've had to set it. But I also don't know how I would do this?

So how to I make the models visible to the controller?


You need to require whatever file your are trying to reference.

For instance, if this module.exports is in a file called Users.js, you would say var Users = require('./Users') (or whatever the filepath to Users is).

That way you can use the exports from this JS file. Hope this helps :)