2016-11-23 55 views
0

我是新的node.js世界,但我正在嘗試使用mongoDB和一些javascript原型開發一個REST API。
擁有模型和原型對象的最佳方法是什麼?我是否需要在原型的同一類中擁有mongo模式定義?nodejs mongo原型最佳實踐

例如:

var Person = function (name) { 
    this.name = name; 
} 

Person.prototype.getSchema = function() { //To-do create mongo schema 
} 

Person.prototype.getName = function() { 
    return this.name; 
} 

這是一個好方法嗎?我必須修改某些內容嗎?

回答

1

我推薦給貓鼬開頭。 在貓鼬會是這樣的:

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) 

然後在你的控制器,你可以導入用戶模型和應用模型。