12

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} 

6 Answers 6

14

I came across this issue and fixed it by adding the following to tsconfig.json

"esModuleInterop": true

Then I could import as normal import mongoose from 'mongoose'

8

Try This

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});


module.exports = mongoose.model('User', UserSchema);

2nd Way -

import * as mongoose from 'mongoose';

type UserSchema = IUser & mongoose.Document;

const User = mongoose.model<UserSchema>('User', new mongoose.Schema({
        email  : { type: String, required: true, unique: true },
          password: { type: String, required: true }
    }));
export = User;
10
  • the line mongoose.model<IUser>('User', UserSchema); now gives an error of Untyped function calls may not accept type arguments.
    – Bill
    Commented Aug 24, 2019 at 7:53
  • Use module.exports if you are using express module.exports= mongoose.model<IUser>('User', UserSchema); and also import IUser in same file
    – Gaurav
    Commented Aug 24, 2019 at 7:58
  • I dont quite understand please could you update your answer to reflect this?
    – Bill
    Commented Aug 24, 2019 at 8:11
  • Check once the answer then let me know
    – Gaurav
    Commented Aug 24, 2019 at 8:47
  • the firstone gives an error of Untyped function calls may not accept type arguments. the second option gives an error An export assignment cannot be used in a module with other exported elements.If I dont export the interface IUser then i get the error Cannot find name 'IUser'
    – Bill
    Commented Aug 24, 2019 at 9:32
1

Make sure that you have "allowSyntheticDefaultImports": true, in tsconfig.json file.

Reference: https://github.com/microsoft/TypeScript-React-Starter/issues/8#issuecomment-301265017

0

I am not sure how you are compiling the typescript but it should work just fine with the defaults set in tsconfig.json file.

  • generate tsconfig.json in your project's root directory by running tsc --init (as mentioned, you can use defaults for this to work with target set even to es5)

  • now you can run tsc -w or ts-node index.ts or however you prefer to build/run your code

Note that the index.ts file must be either in your project's root or you will need to specify the path in the tsconfig.json (the rootDir options which is commented out by default and uses path relative to the tsconfig file).

Also note that if you are running tsc -w or some other command that compiles/runs the code from some other directory than the one where tsconfig.json is located, you will need to provide a path to it, i.e. tsc -p path_to_config -w

0

I Have the same issue I noticed that I missed the tsconfig.json

0
import { model, Schema } from 'mongoose';
...
export default model<IUser>('User', UserSchema);
1
  • 2
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. Commented Feb 5, 2021 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.