我正在尝试在node和mongoose中创建一个登录页面,并且一旦我运行包含一些名为seed.js的测试数据的文件,就会弹出该错误
const mongoose = require('mongoose');
const db = require('./dbconn');
const users = [
{ username: 'username', password: 'password' },
{ username: 'kelvin', password: 'password' },
];
const seed = async () => {
try {
await db.User.remove();
console.log('DROP ALL USERS');
await Promise.all(
users.map(async user => {
const data = await db.User.create(user);
await data.save();
}),
);
console.log('CREATED USERS', JSON.stringify(users));
await Promise.all(
polls.map(async poll => {
poll.options = poll.options.map(option => ({ option, votes: 0 }));
const data = await db.Poll.create(poll);
const user = await db.User.findOne({ username: 'username' });
data.user = user;
user.polls.push(data._id);
await user.save();
await data.save();
}),
);
console.log('CREATED POLLS', JSON.stringify(polls));
} catch (err) {
console.error(err);
}
};
seed();
还有我的schema.js文件,该文件位于名为dbconn-的文件夹中
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
var userSchema = new mongoose.Schema({
username:{
type:String,
required:true,
unique:true,
}
,password:{
type:String,
required:true,
},
created:{
type:Date,
default:Date.now
},
});
userSchema.pre('save',async function(next){
try{
if(!this.isModified('password')){
return next();
}
const hashed = await bcrypt.hash(this.password,10);
this.password=hashed;
return next();
}
catch(err){
return next(err);
}
})
module.exports = mongoose.model('User',userSchema);
dbconn文件已经有一个index.js文件,该文件已经使用mongoose建立了mongodb连接