Skip to content
Advertisement

Node.JS – Product is not a constructor error

My code is as follows and gets me "message": "Product is not a constructor" using postman. Router seems to be properly configured but now I don’t know what is the issue. File product constructor is placed at the right direction. When running node server I get no errors in terminal.

product constructor

const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  price: Number
});

module.export = mongoose.model('Product', productSchema);

Router for POSTS

const mongoose = require('mongoose');
const Product = require('../models/product'); //import schema, product constructor


//POSTs to products
router.post('/', (req,res,next) => {

    //ObjectId method to add new ID
    const product = new Product({
      _id: new mongoose.Types.ObjectId(),
      name: req.body.name,
      price: req.body.price
    });

    //mongoose method to save data
    product
      .save()
      .then(result => {
      console.log(result);
    })
    .catch(err => console.log(err));

    res.status(201).json({
      message: 'sending POSTs to /products',
      createdProduct: product
    });
});

Advertisement

Answer

It should be module.exports (doc), not module.export:

module.exports = mongoose.model('Product', productSchema);

Right now your module essentially exports a default value (an empty object).


As a sidenote, Schema is expected to be used as a constructor. While the function itself is written the way it’ll recall itself with proper syntax if used without new:

if (!(this instanceof Schema)) {
  return new Schema(obj, options);
}

… you can both avoid this (albeit miniscule) loss of performance and, what’s more important, show the actual intent clearly:

const productSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  name: String,
  price: Number
});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement