【发布时间】:2019-12-29 08:09:33
【问题描述】:
使用 ES6 Imports & Exports 我觉得我应该能够将导入声明为
import mongoose, { Schema, Document } from 'mongoose'; 但我收到错误 Module '"mongoose"' has no default export.
以下内容确实有效,但显然不是进行此导入的正确方法。导出默认 id 也喜欢删除。
import * as mongoose from 'mongoose';
import { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
password: string;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
export default mongoose.model<IUser>('User', UserSchema);
然后我将它与
一起使用import UserModel, { IUser } from '../models/example'
import * as bcrypt from 'bcrypt';
class User {
static register = async (req: Request, res: Response) => {
const email = req.body.email;
const password = req.body.password;
const alreadyRegistered = await UserModel.findOne({email}).exec();
if (!alreadyRegistered) {
const hashedPassword = await bcrypt.hash(password,10);
if (!hashedPassword) {
res.status(500).send({ message: "Failed to encrypt your password" });
} else {
const user = new UserModel(<IUser>{email:email, password:hashedPassword});
const saved = await user.save();
if (!saved) {
res.status(500).send({ message: "Failed to register you" });
} else {
res.status(200).send({ message: "You are now registered" });
}
}
} else {
res.status(400).send({ message: "You have already registered" });
}
};
}
export {User}
【问题讨论】:
标签: node.js typescript mongoose