Home > Software engineering >  Why I'm not able to export this moongose Class?
Why I'm not able to export this moongose Class?

Time:06-24

Here's my User class/schema:

import mongoose from "mongoose";

let UserSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    enabled: {
        type: Boolean
    }
}, {
    collection: 'Users'
});

const User = mongoose.model('User', UserSchema)
export default User

I'm doing import feature, so on another file (i.e. routes/account.js) I've:

import User from "../models/User";

but when I start the nodejs project, it says:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\repos\Web\MyApp\backend\models\User' imported from C:\repos\Web\MyApp\backend\routes\account.js
    at new NodeError (node:internal/errors:371:5)
    at finalizeResolution (node:internal/modules/esm/resolve:418:11)
    at moduleResolve (node:internal/modules/esm/resolve:981:10)
    at defaultResolve (node:internal/modules/esm/resolve:1078:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:530:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:251:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:79:40)
    at link (node:internal/modules/esm/module_job:78:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
Program node index.js exited with code 1

What's wrong?

Data structure:

enter image description here

package.json:

{
    "name": "MyApp",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "type": "module",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "supervisor index.js"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "axios": "^0.27.2",
        "bcryptjs": "^2.4.3",
        "body-parser": "^1.20.0",
        "cors": "^2.8.5",
        "crypto": "^1.0.1",
        "crypto-js": "^4.1.1",
        "crypto.js": "^3.0.0",
        "dotenv": "^16.0.1",
        "express": "^4.18.1",
        "http-errors": "^2.0.0",
        "jsonwebtoken": "^8.5.1",
        "moment": "^2.29.3",
        "mongoose": "^6.4.0",
        "supervisor": "^0.12.0"
    }
}

CodePudding user response:

When we use import ,we have to use extension like this:

import User from "../models/User.js";
                                 ^^
  • Related