Import of Mongoose schema in Node js app not working properly

Viewed 2770

I'm getting an error message whenever i try to import in my basic exercise app

Exercise-Tracker-MERN\backend\models\exercise.model.js:1
(function (exports, require, module, __filename, __dirname) { import Schema from "mongoose";
import Schema from "mongoose";
const mongoose = require("mongoose");

const exercise = new Schema(
  {
    username: { type: String, required: true },
    description: { type: String, required: true },
    duration: { type: Number, required: true },
    date: { type: Date, required: true }
  },
  {
    timestamps: true
  }
);

const Exercise = mongoose.model("Exercise", userSchema);
module.exports = Exercise;

I'm following tutorial: https://www.youtube.com/watch?v=7CqJlxBYj-M

3 Answers

I can see multiple errors in your code. If you are using nodejs without any support for es6 you cannot use import statement instead use require. Also, you are creating Exercise model using userSchema which is not defined.

Please try this

const mongoose = require("mongoose");

const exercise = new mongoose.Schema(
  {
    username: { type: String, required: true },
    description: { type: String, required: true },
    duration: { type: Number, required: true },
    date: { type: Date, required: true }
  },
  {
    timestamps: true
  }
);

const Exercise = mongoose.model("Exercise", exercise);
module.exports = Exercise;

You need to import mongoose first

import mongoose from 'mongoose';

const { Schema } = mongoose;

Schema comes from the imported of mongoose

import { Schema } from "mongoose"; es6 syntax(and your node version may not recognize it yet) try const { Schema } = require("mongoose");

if the syntax is not the issue it may be that because you did not deconstruct the Schema out of the mongoose module instead of using the default export

Related