Reputation: 93
I'm trying to create a REST api using express and mongoose. Below is the code for User model (user.server.model.js).
const mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
name: {
first: { type: String, required: true },
last: { type: String, required: true }
},
loginId: { type: String, required: true, unique: true },
password: { type: String, required: true },
location: String,
meta: { age: Number, website: String },
isActive: Boolean,
createdOn: { type: Date, default: Date.now },
updatedOn: Date
});
var User = mongoose.model('User', userSchema);
exports.User = User;
I'm trying to use this User model in express route (routes.js) as below:
const express = require('express'),
User = require('../models/user.server.model'),
router = express.Router();
router.route('/users')
.post((req, res) => {
let user = new User({
name: req.body.name,
loginId: req.body.loginId,
password: req.body.password,
location: req.body.location,
meta: req.body.meta,
createdOn: req.body.createdOn,
updatedOn: req.body.updatedOn
});
user.save((err) => {
if (err) {
res.send(err);
}
else{
res.json({ message: 'User created' });
}
});
});
module.exports = router;
But when I try to test this api using Postman extension in Chrome I'm getting below error
TypeError: User is not a constructor
Node Version: 6.0
Can anyone please advise whats going wrong here.
Upvotes: 0
Views: 185
Reputation: 311835
You're using the require
value directly as User
, so you should change exports.User
to module.exports
in user.server.model.js:
module.exports = User;
Upvotes: 1