Schema and Model Import

6 viewsmongodbmongoosenode.js
0

Using Nodejs, MongoDb and Mongoose I’m encountering an error and I can’t figure out why. The connection to the Db takes place without problems and the code works well if the creation of the Model and the Schema take place in the same File of the routes. If, on the other hand, the Model and the Schema are in another file and are exported and imported into the Route File, the route that manages the creation and momorization in the db of the new user fails. You might think that the problem is in importing the Model, but it is not so because if you go to make a console.log(User) you see that the Model is present. The error generated is a common error (MongooseError: Operation ‘as.insertOne()’ buffering timed out after 10000ms at Timeout.)but the problem is to be attributed to what has been said above. I hope I have been clear. I believe I export and import the Model correctly.Everything is in local.

As said the code works if in the same file the Schema and the Model are present, importing the Model the console.log(User) shows me Model { User }.

index.js

  const db = require("./server");
  const express = require("express");
  const app = express();
  const mongoose = require("mongoose");

  app.use(express.json());

  const User = require("../model/userModel");

  // const User = mongoose.model("User", aSchema);
  app.post("/", async (req, res) => {
    try {
      // const aSchema = new mongoose.Schema({
      //   name: {
      //     type: String,
      //     required: [true, "Insert your name:"],
      //   },

      // });

      // const User = mongoose.model('User', aSchema);

      // const silence = await User.create({ name: "Silence" });
      console.log(User);
      // res.send(silence);
    } catch (error) {
      console.error(error);
      res.status(500).json({
        status: "error",
        message: "An error occurred while creating user.",
        error: error.message,
      });
    }
  });

  db().then(() => {
    const port = 3000;
    app.listen(port, () => {
      console.log(`Server listening on port${port}`);
    });
  });

  module.exports = app;

userModel.js

    const mongoose = require("mongoose");

    const aSchema = new mongoose.Schema({
      name: {
        type: String,
        required: [true, "Insert your name:"],
      }

    });


    const user = mongoose.model('user', aSchema);

    module.exports = user;

server.js:

    const mongoose = require("mongoose");

    async function main() {
      try {
        await mongoose.connect(
          "mongodb+srv://noel:Mypassword@cluster0.jda2xgx.mongodb.net/?retryWrites=true&w=majority"
        ),
          {
            useNewUrlParser: true,
            useUnifiedTopology: true,
          };
        console.log("Database connection successfully established!");
    
      } catch (error) {
        console.error("Error connecting to MongoDB:", error);
      }
    }

    module.exports = main;