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
JavaScript
x
9
1
const mongoose = require('mongoose');
2
const productSchema = mongoose.Schema({
3
_id: mongoose.Schema.Types.ObjectId,
4
name: String,
5
price: Number
6
});
7
8
module.export = mongoose.model('Product', productSchema);
9
Router for POSTS
JavaScript
1
28
28
1
const mongoose = require('mongoose');
2
const Product = require('../models/product'); //import schema, product constructor
3
4
5
//POSTs to products
6
router.post('/', (req,res,next) => {
7
8
//ObjectId method to add new ID
9
const product = new Product({
10
_id: new mongoose.Types.ObjectId(),
11
name: req.body.name,
12
price: req.body.price
13
});
14
15
//mongoose method to save data
16
product
17
.save()
18
.then(result => {
19
console.log(result);
20
})
21
.catch(err => console.log(err));
22
23
res.status(201).json({
24
message: 'sending POSTs to /products',
25
createdProduct: product
26
});
27
});
28
Advertisement
Answer
It should be module.exports
(doc), not module.export
:
JavaScript
1
2
1
module.exports = mongoose.model('Product', productSchema);
2
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
:
JavaScript
1
4
1
if (!(this instanceof Schema)) {
2
return new Schema(obj, options);
3
}
4
… you can both avoid this (albeit miniscule) loss of performance and, what’s more important, show the actual intent clearly:
JavaScript
1
6
1
const productSchema = new mongoose.Schema({
2
_id: mongoose.Schema.Types.ObjectId,
3
name: String,
4
price: Number
5
});
6