Whenever I want to make a POST request using Postman I get this error: TypeError: Item is not a constructor. Any idea why? I have my code here:
const Item = require('../model/item.js'); const createItem = async(req,res) => { const category = await categoryService.findCategoryByName(req.body.category); const newItem = new Item({ name: req.body.name, created: new Date(), category: [category], quantity: req.body.quantity, }); try{ await newItem.save(); res.status(201).json(newItem); }catch(error){ res.status(404).json({message: error.message}); } };
And item.js:
const mongoose = require('mongoose'); const categSchema = require("./category.js") const itemSchema = mongoose.Schema({ name: {type: String, required: true}, created: {type: Date, required: true, unique: true}, category: [categSchema.categorySchema], quantity: {type: Number, required: true} }); var itemData = mongoose.model("itemData", itemSchema); module.exports.itemData = itemData; module.exports.itemSchema = itemSchema;
Advertisement
Answer
You’re importing the full exports
object, not just part of it. That object is not a constructor function (it’s not a function at all).
Looking at your exports: According to the documentation (I don’t use Mongoose), mongoose.model
returns a constructor function. So:
Export it using standard naming for constructor functions (
ItemData
, rather thanitemData
), andImport it rather than the entire exports object
So for instance:
module.exports.ItemData = mongoose.model("itemData", itemSchema); module.exports.itemSchema = itemSchema;
and to import it (by destructuring it from the exports object):
const { ItemData } = require("../model/item.js"); // ^−−−−−−−−−−^−−−−−−−−− destructuring
Then, new ItemData
should work.
Alternatively, import the whole thing (const item = require(/*...*/);
) and then use new item.ItemData
.