将 MongoDB 文档转换为强类型 class

Casting a MongoDB document to a strongly typed class

谁能告诉我如何将从 MongoDB 检索到的文档转换为我自己创建的 class?我不想使用 Mongoose,我正在使用 github.com/christkv/mongodb-legacy v2.0.13

从 MongoDB

返回的文档的值
{
    id { MongoDb ID},
    email: 'me@home.com',
    passwordHash: 'a$Wjan4CloaZRYj60MGsDb6e7x11e1QYkjW3N2q5JYBDaKBNipLti36',
    passwordSalt: 'a$Wjan4CloaZRYj60MGsDb6e',
    id: 'mrpmorris'
}

执行失败的代码

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

抛出异常

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

用户class

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: 'a$Wjan4CloaZRYj60MGsDb6e7x11e1QYkjW3N2q5JYBDaKBNipLti36',
    passwordSalt: 'a$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);