我尝试创建一个与个人资料链接的新用户。这是我的模特:
UserModel:
import mongoose from 'mongoose';
import {RoleModel} from "./RoleModel";
const bcrypt = require('bcrypt');
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true
},
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
email: {
type: String,
required: true
},
mobile: {
type: String,
required: () => { return !(!!this.phone) }
},
phone: {
type: String,
required: () => { return !(!!this.mobile) }
},
role: {
type: mongoose.Schema.Types.ObjectId,
ref: RoleModel,
required: true
},
password: {
type: String,
required: true
}
},
{
validateBeforeSave: true,
timestamps: true
});
UserSchema.methods.validPassword = async (password, user) => {
try {
return await bcrypt.compare(password, user.password);
} catch (err) {
await Promise.reject(new Error('Error during authentication'));
}
};
export const UserModel = mongoose.model("users", UserSchema);
RoleModel:
import mongoose from 'mongoose';
const RoleSchema = new mongoose.Schema(
{
name: {
type: String,
required: true
}
},
{
validateBeforeSave: true,
timestamps: true
}
);
export const RoleModel = mongoose.model("role", RoleSchema);
我尝试使用它们插入一个新用户,并在创建中按名称获取角色。不幸的是,在保存过程中我总是遇到Segmentation fault (core dumped)
或错误。保存动作之前似乎找不到我的角色。
这是我的方法:
import {UserModel} from "./Model/UserModel";
import mongoose from "mongoose";
const bcrypt = require('bcrypt');
let user = new UserModel({
username: 'Fubar',
firstname: 'Foo',
lastname: 'Bar',
email: 'foobar@fubar.com',
mobile: 'my-awesome-mobile',
role: RoleModel.findOne({name: 'DEFAULT_ROLE'}, (err, role) => {
if (err) return handleError(err);
return role;
}),
password: bcrypt.hash('myPlaintextPassword', 15, (err, hash) => {
if (err) return handleError(err);
return hash;
});
});
user.save(err => {if (err) return handleError(err);});
能否请您帮助我有效地保存用户?我想我误会了一些东西,但是尽管进行了测试,但还是没有指出。.
谢谢