Using ES6 Imports & Exports I feel like I should be able to declare the import as
import mongoose, { Schema, Document } from 'mongoose';
but I get the error Module '"mongoose"' has no default export.
The below does work but it clearly isn't the right way to go about this import. The export default id like to remove too.
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);
And then im using it with
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}