Wednesday 27 March 2019

FindOne error when creating new Model Mongoose

Hi there​I try to create a new User linked with a profile. Here is my models :​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); ​​With them I try to insert a new User and getting a role by name in creation. Unfortunately, I always get a `Segmentation fault (core dumped)` or Error during save. It seems my role is not found before saving action.​Here my methods :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); }); ​Could you help me to reach to save efficiently my user please ? I guess I misunderstood something, but despite of my tests, I did not succeed to point it out..​Thanks,

Submitted March 27, 2019 at 01:26PM by CyrilZN

No comments:

Post a Comment