arcyqwerty
arcyqwerty

Reputation: 10695

How to 'require' a database schema in nodejs

What is the best way to require a mongoose Schema in nodejs?

Originally I had these inside the app.js file but that is getting a bit large and unwieldy with more models.

Now I want to move them into a models folder and use Model = require('./models/model') to import them into app.js

How do I get it such that Model is populated with the actual model?

(exports = mongoose.model(...) fails and gives me a blank object; exports.model = mongoose.model(...) requires me to do Model.model to access it -- neither of these are the desired behavior)

===

Edit1

So basically I have taken

var mongoose = require('mongoose');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

var UserSchema = new Schema({
  username: String,
  password: String,
  first_name: String,
  last_name: String,
  email: String
});
User = mongoose.model('User', UserSchema);

and put it into ./models/user.js

How do I get it such that its the equivalent of having this in the app.js?

Upvotes: 1

Views: 4618

Answers (1)

Mike S.
Mike S.

Reputation: 4879

In your app.js server file, include the model.js file like this:

var Model = require('./models/model');  //whatever you want to call it

You can then instantiate it in your server file like this:

//Initiate the  Business API endpoints
var model = new Model(mq, siteConf);
model.getUser(id, function() {
    // handle result
});

----

Then in your file you place in models folder named model.js (or whatever you want) you can set it up like this:

var mongoose = require('mongoose'); 

//MongoDB schemas
var Schema = mongoose.Schema;

var User = new Schema({
  username: String,
  password: String,
  first_name: String,
  last_name: String,
  email: String
});
var UserModel = mongoose.model('User', User);

// your other objects defined ...


module.exports = function(mq, siteConf) {
//MongoDB
mongoose.connect(siteConf.mongoDbUrl);


// ------------------------
// READ API
// ------------------------

// Returns a user by ID
function getUser(id, found) {
    console.log("find user by id: " + id);
    UserModel.findById(id, found);
}

// Returns one user matching the given criteria
// mainly used to match against email/login during login
function getUserByCriteria(criteria, found) {
    console.log("find user by criteria: " + JSON.stringify(criteria));
    UserModel.findOne(criteria, found);
}



    // more functions for your app ...



return {
    'getUser': getUser, 
            'getUserByCriteria': getUserByCriteria
   };
};

Upvotes: 2

Related Questions