简体   繁体   中英

mongoose best practices for objects

I have a user.js file that contains all my mongoose schema and methods, roughly like this:

var userSchema = mongoose.Schema({
  name: { type: String, required: true, trim: true },
  surname: { type: String, required: true },
});

var User = mongoose.model('User', userSchema);

Now, Is it best to expose functions that model the data? like this:

exports.addUser = function(data, next){
  user = new User(data);
  user.save(next);
};

exports.getAll = function(next){
  var query = User.find();
  query.exec(next);
};

or to expose just the User object to be used elsewhere like this?

module.exports = User; //or
exports.User = User;

I am also facing a problem derived from the second solution, suppose I want to add a list of cars to my userSchema , and the car schema is defined in another file car.js , then it means that I will have to expose the carSchema for my user.js file, right? This means I am actually nullifying the second solution I provided above, then, what is the right way of doing this sort of things?

Interesting question.

This is probably just a "syntactic sugar" thing but I am sticking with the second variant because there is IMHO no need to capsule the generation etc. mongoose is the wrapper around such stuff and one can then use the pure mongoose Models and Schemas. Does this sounds reasonable for you?

exports.User = User;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM