user10272439
user10272439

Reputation:

Pro.find is not a function error in mongoose model exports

This is my server.js where I can run the code to initialize my server through localhost:7000. And the route that I am running is product.js:

Product Route:

const express = require('express');
const router = express.Router();

const Pro = require('../model/Product');

router.get('/', (req, res) => {
    Pro.find()
    .sort({ entrydate: -1 })
    .then(product => res.json(product));
});
router.post('/product', ( req, res ) => {
    res.send('Posting a response')
});
module.exports = router;

Which gets the error:

TypeError: Product.route is not a function

Product Model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({
  // Objects and Properties are here
});

const Product = mongoose.model('products', ProductSchema);
module.exports = { Product };

How do I get out of this mess?

Upvotes: 3

Views: 800

Answers (3)

cmoshe
cmoshe

Reputation: 369

use module.exports = Product in your Product Route

Upvotes: 0

u-ways
u-ways

Reputation: 7764

You're exporting Product within an object:

module.exports = { Product };

Therefore, what you're doing when you try to find a product is:

{ Product }.find();

Which is probably what you don't want. Instead:

module.exports = Product;

or instead of creating a Product variable:

module.exports = mongoose.model('products', ProductSchema);

Both should export products model only and fix your problem.

Upvotes: 4

mehta-rohan
mehta-rohan

Reputation: 1341

Learn about destructuring in javascript. You can handle this by

const {Product} = require('../model/Product'); //recommended

or

const any_variable_name = require('../model/Product').Product;

module.exports = variable_name will also help but if you have multiple variables to export then you have to write this whole line multiple times. whereas module.exports = {v1,v2,v3...vn} will be more readable

Upvotes: 1

Related Questions