0
votes

I know this question has been asked before but I couldn't find one for my situation. I am making a schema for my items and making my routes using mongo but for some reason, it keeps giving me an error.

throw new mongoose.Error.MissingSchemaError(name); ^ MongooseError [MissingSchemaError]: Schema hasn't been registered for model "Item". Use mongoose.model(name, schema) at new MissingSchemaError (C:\Users\samib\Documents\goodies-server\node_modules\mongoose\lib\error\missingSchema.js:22:11) at Mongoose.model (C:\Users\samib\Documents\goodies-server\node_modules\mongoose\lib\index.js:501:13) at Object. (C:\Users\samib\Documents\goodies-server\src\routes\itemRoutes.js:5:23) at Module._compile (internal/modules/cjs/loader.js:955:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10) at Module.load (internal/modules/cjs/loader.js:811:32) at Function.Module._load (internal/modules/cjs/loader.js:723:14) at Module.require (internal/modules/cjs/loader.js:848:19) at require (internal/modules/cjs/helpers.js:74:18) at Object. (C:\Users\samib\Documents\goodies-server\src\index.js:7:20) at Module._compile (internal/modules/cjs/loader.js:955:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10) at Module.load (internal/modules/cjs/loader.js:811:32) at Function.Module._load (internal/modules/cjs/loader.js:723:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10) at internal/main/run_main_module.js:17:11 { message: Schema hasn't been registered for model "Item".\n + 'Use mongoose.model(name, schema)', name: 'MissingSchemaError' } [nodemon] app crashed - waiting for file changes before starting...

This is my Item model--


const itemSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  title: {
    type: String,
    required: true
  },
  category: {
    type: String,
    required: true
  },
  detail: {
    type: String,
    requiredL: true
  },
  condition: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  }
});

mongoose.model("Item", itemSchema);

This is the itemRoutes--

const express = require("express");
const mongoose = require("mongoose");

const Item = mongoose.model("Item");

const router = express.Router();

router.get("/items", async (req, res) => {
  const items = await Item.find();
  res.send(items);
});

router.post("/items", requireAuth, async (req, res) => {
  const item = new Item({
    title: req.body.title,
    category: req.body.category,
    detail: req.body.detail,
    condition: req.body.condition,
    price: req.body.price
  });
  await item.save();
  res.send(item);
});

router.put("/items/:id", requireAuth, async (req, res) => {
  const item = await Item.findByIdAndUpdate(
    req.params.id,
    {
      title: req.body.title,
      category: req.body.category,
      detail: req.body.detail,
      condition: req.body.condition,
      price: req.body.price
    },
    { new: true }
  );

  if (!item)
    return res.status(404).send("The item with the given ID was not found.");

  res.send(item);
});

router.delete("/items/:id", requireAuth, async (req, res) => {
  const item = await Item.findByIdAndRemove(req.params.id);

  if (!item)
    return res.status(404).send("The item with the given ID was not found.");

  res.send(item);
});

module.exports = router;

This is the index.js--

const requireAuth = require("./middleware/requireAuth");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const authRoutes = require("./routes/authRoutes");
const itemRoutes = require("./routes/itemRoutes");

const app = express();

app.use(bodyParser.json());
app.use(authRoutes);
app.use(itemRoutes);

app.get("/", requireAuth, (req, res) => {
  res.send(`Your email: ${req.user.email}`);
});

mongoose
  .connect("mongodb://localhost/goodies")
  .then(() => console.log("Connected to MongoDB..."));

app.listen(1000, () => {
  console.log("Listening on PORT 1000...");
});

It's silly because this is a pretty easy node project not sure what is going on.

2

2 Answers

2
votes

You need to call model function on mongoose.connection object. Here is how my mongo.js file looks like:

let mongoose = require('mongoose');
let mongoConnetionUrl = `mongodb://${process.env.MONGO_DB_HOST}:${process.env.MONGO_DB_PORT}/${process.env.MONGO_DB_DATABASE}`;

mongoose.connect(mongoConnetionUrl, {useNewUrlParser: true});

class Mongo {
  constructor(){
    this.conn = mongoose.connection;
    this.Schema = mongoose.Schema;
  }

  getConnection(){
    return this.conn;
  }

  getSchema(){
    return this.Schema;
  }
}

module.exports = new Mongo();

For Model file:

const conn = require('/mongo').getConnection();
const Schema = require('/mongo').getSchema();
const itemSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  title: {
    type: String,
    required: true
  },
  category: {
    type: String,
    required: true
  },
  detail: {
    type: String,
    requiredL: true
  },
  condition: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  }
});
module.exports = conn.model('Item', itemSchema);
0
votes

in my item models file, I added a const to my mongoose.model, then I exported that const.

const Item = mongoose.model("Item", itemSchema);
module.exports = Item;

In my itemRoues.js I just used a require statment

const Item = require("../models/Item");

I hope this works to whoever else it seemed to work for me can't explain why. Would love to learn if someone else can explain still. Thanks again guys