[英]nodejs mongo prototype best practices
I'm new in the node.js world, but I'm trying to do a REST API with mongoDB and some javascript prototyping. 我是node.js世界的新手,但我正在尝试使用mongoDB和一些javascript原型制作REST API。
What is the best approach to have a model and the prototype object? 拥有模型和原型对象的最佳方法是什么? Do i need to have the mongo schema definition in the same class of the prototype? 我是否需要在原型的同一类中具有mongo模式定义?
For example: 例如:
var Person = function (name) {
this.name = name;
}
Person.prototype.getSchema = function () { //To-do create mongo schema
}
Person.prototype.getName = function () {
return this.name;
}
Is that a good approach? 那是一个好方法吗? Do I have to modify something? 我需要修改吗?
I recommend to you starting with mongoose. 我建议您从猫鼬开始。 In mongoose would be something like this: 在猫鼬中将是这样的:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var userSchema = new Schema({
username: String,
password: String
})
userSchema.statics = {
getByName(name) {
return this.find({name})
.exec(function(err, user) {
console.log(user);
});
}
}
module.exports = mongoose.model('User', userSchema)
Then in your controller you can import the User model and use the model method. 然后,您可以在控制器中导入用户模型并使用模型方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.