我需要将一些虚拟用户信息播种到mongoose数据库,当真实用户在线提交表单时,用户模型会检查密码确认,这需要保持原状。我正在运行mongod并且在我的终端中使用gulp但是每次我使用Node运行我的种子文件时都会得到ValidatorError。任何人都可以建议如何解决这个问题。
用户模型。
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
username: { type: String, required: true },
email: { type: String, required: true },
postcode: { type: String, required: true },
password: { type: String, required: true }
});
userSchema.pre('save', function hashPassword(next) {
if (this.isModified('password')) {
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(8));
}
next();
});
userSchema
.virtual('passwordConfirmation')
.set(function setPasswordConfirmation(passwordConfirmation) {
this._passwordConfirmation = passwordConfirmation;
});
userSchema.pre('validate', function checkPassword(next) {
if (this.isModified('password') && this._passwordConfirmation !== this.password) this.invalidate('passwordConfirmation', 'does not match');
next();
});
userSchema.methods.validatePassword = function validatePassword(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = mongoose.model('User', userSchema);
种子档案。
const mongoose = require('mongoose');
const { port, db, secret } = require('../config/env');
mongoose.Promise = require('bluebird');
mongoose.connect(db);
const User = require('../models/user');
const Event = require('../models/event');
User.collection.drop();
Event.collection.drop();
User.create([{
username: 'dan123',
email: 'dan@dan.com',
postcode: 'SE270JF',
password: '123'
}, {
username: 'ben123',
email: 'ben@ben.com',
postcode: 'SE191SB',
password: '123'
}])
.then(user => {
console.log(`${user.length} users created`);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
mongoose.connection.close();
});
我必须使用我当前的软件包设置,因此无法在此范围之外应用建议。所有帮助表示赞赏。
答案 0 :(得分:1)
您收到此错误是因为您创建的验证要求您在创建过程中提供与passwordConfirmation
匹配的password
。
您可以通过将passwordConfirmation
字段添加到种子数据中来实现这一目标:
User.create([{
username: 'dan123',
email: 'dan@dan.com',
postcode: 'SE270JF',
password: '123'
passwordConfirmation: '123',
}, {
username: 'ben123',
email: 'ben@ben.com',
postcode: 'SE191SB',
password: '123',
passwordConfirmation: '123',
}])