2015-01-10 65 views
1

誰能告訴我如何將從MongoDB檢索的文檔轉換爲我自己創建的類?我不想用貓鼬,我使用github.com/christkv/mongodb-legacy v2.0.13將MongoDB文檔強制類型化

文檔的值從MongoDB的

{ 
    id { MongoDb ID}, 
    email: '[email protected]', 
    passwordHash: '$2a$04$Wjan4CloaZRYj60MGsDb6e7x11e1QYkjW3N2q5JYBDaKBNipLti36', 
    passwordSalt: '$2a$04$Wjan4CloaZRYj60MGsDb6e', 
    id: 'mrpmorris' 
} 

返回未能執行代碼

var user = Object.create(User.prototype, document) 

拋出

TypeError: Property description must be an object: $2a$04$Wjan4CloaZRYj60MGsDb6e 
    at defineProperties (native) 
    at Function.create (native) 

User類的異常

var assert = require('assert') 
var bcrypt = require('bcrypt') 

var User = (function() { 
    function User() { 
     this.passwordSalt = "hello" 
    } 

    User.prototype.constructor = User 
    User.prototype.setPassword = function (newPassword, callback) { 
     var self = this 
     assert.ok(newPassword != null, "newPassword cannot be null") 
     assert.ok(newPassword.length >= 8) 
     bcrypt.genSalt(2, function (err, salt) { 
      self.passwordSalt = salt 
      bcrypt.hash(newPassword, salt, function (err, hash) { 
       self.passwordHash = hash 
       callback(err); 
      }) 
     }); 
    } 

    User.prototype.checkPassword = function (password, callback) { 
     var self = this 
     bcrypt.hash(self.passwordHash, self.passwordSalt, function (err, hash) { 
      callback(err, hash === self.passwordHash) 
     }) 
    } 


    return User 
})() 

exports.User = User 
+1

爲什麼不把用戶文檔作爲構造函數中的參數? – cbass

回答

3

你得到一個錯誤,因爲Object.create預期性描述符作爲其第二個參數,某事像

var doc = { 
    email: '[email protected]', 
    passwordHash: '$2a$04$Wjan4CloaZRYj60MGsDb6e7x11e1QYkjW3N2q5JYBDaKBNipLti36', 
    passwordSalt: '$2a$04$Wjan4CloaZRYj60MGsDb6e', 
    id: 'mrpmorris' 
}; 

var user = Object.create(User.prototype, { 
    // regular 'value property' 
    email:  { writable: true, configurable: true, value: doc.email  }, 
    passwordHash: { writable: true, configurable: true, value: doc.passwordHash }, 
    passwordSalt: { writable: true, configurable: true, value: doc.passwordSalt }, 
    id:   { writable: true, configurable: true, value: doc.id   } 
}); 

請參考MDN的細節

另外,作爲@cbass建議,你可能將mongo文件對象傳遞給User構造函數

function User(doc) { 
    this.id = doc.id; 
    this.email = doc.email; 
    this.passwordHash = doc.passwordHash; 
    this.passwordSalt = doc.passwordSalt; 
} 
//... 
var user = new User(doc); 
+0

感謝您的全面回答!我已決定取消選擇我的模型,並創建對文檔執行操作的函數 –