user3692927
user3692927

Reputation: 64

Model file, and DB interaction

I have a model file, such as

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

var User = new Schema({
    firstname   : {type: String, required: false},
    lastname    : {type: String, required: false},
    email       : {type: String, required: true}
});

module.exports = mongoose.model('user', User);

I want to create functions to update, save or delete a user from the database.

Where should I be putting such DB-related functions? I was thinking in the route files, but also in the model.js file itself, or elsewhere?

Upvotes: 1

Views: 68

Answers (1)

Eugene Kostrikov
Eugene Kostrikov

Reputation: 7119

In the same file, certainly. Think of model.js as an interface that has convenience methods that allow you to work with DB. It's sole purpose is to define schema, add some helpers (if necessary) and expose a one model (it's important) to the outside world.

Read more about mongoose methods and statics. This might be helpful.

Also it's wise to name the file that defines model after the model itself. user.js in your case.

Upvotes: 1

Related Questions