gpt4 book ai didi

javascript - 将 MongoDB 文档转换为强类型类

转载 作者:行者123 更新时间:2023-11-30 12:30:31 25 4
gpt4 key购买 nike

谁能告诉我如何将从 MongoDB 检索到的文档转换为我自己创建的类?我不想使用 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)

抛出的异常

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详情

或者,正如@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);

关于javascript - 将 MongoDB 文档转换为强类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27879568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com