nodejs mongo 原型最佳实践
nodejs mongo prototype best practices
我是 node.js 世界的新手,但我正在尝试使用 mongoDB 和一些 javascript 原型制作 REST API。
拥有模型和原型对象的最佳方法是什么?我是否需要在原型的相同 class 中包含 mongo 架构定义?
例如:
var Person = function (name) {
this.name = name;
}
Person.prototype.getSchema = function () { //To-do create mongo schema
}
Person.prototype.getName = function () {
return this.name;
}
这是一个好方法吗?我需要修改什么吗?
我建议你从猫鼬开始。
在猫鼬中会是这样的:
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)
然后在你的控制器中你可以导入用户模型并使用模型方法。
我是 node.js 世界的新手,但我正在尝试使用 mongoDB 和一些 javascript 原型制作 REST API。
拥有模型和原型对象的最佳方法是什么?我是否需要在原型的相同 class 中包含 mongo 架构定义?
例如:
var Person = function (name) {
this.name = name;
}
Person.prototype.getSchema = function () { //To-do create mongo schema
}
Person.prototype.getName = function () {
return this.name;
}
这是一个好方法吗?我需要修改什么吗?
我建议你从猫鼬开始。 在猫鼬中会是这样的:
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)
然后在你的控制器中你可以导入用户模型并使用模型方法。