将MongoDB文档转换为强types的类

任何人都可以告诉我如何将从MongoDB检索到的文档转换为我自己创build的类? 我不想使用Mongoose,我正在使用github.com/christkv/mongodb-legacy v2.0.13

从MongoDB返回的文档的值

{ id { MongoDb ID}, email: 'me@home.com', passwordHash: '$2a$04$Wjan4CloaZRYj60MGsDb6e7x11e1QYkjW3N2q5JYBDaKBNipLti36', passwordSalt: '$2a$04$Wjan4CloaZRYj60MGsDb6e', id: 'mrpmorris' } 

无法执行的代码

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

引发exception

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

用户类

 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 

你会得到一个错误,因为Object.create需要属性描述符作为它的第二个参数

 var doc = { email: 'me@home.com', 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

或者,如@cbassbuild议的那样,您可以将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);