简体   繁体   English

mongoose对象的最佳实践

[英]mongoose best practices for objects

I have a user.js file that contains all my mongoose schema and methods, roughly like this: 我有一个user.js文件,其中包含我所有的mongoose模式和方法,大致如下:

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? 或者只公开要在别处使用的User对象?

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? 我也面临从第二个解决方案中得到的问题,假设我想在我的userSchema添加一个汽车列表,并且汽车架构在另一个文件car.js中定义,那么这意味着我必须公开carSchema for我的user.js文件,对吗? 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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