0

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.

Dinu
  • 93
  • 2
  • 13
  • 1
    You're using the `require` value directly as `User`, so you should change `exports.User` to `module.exports` in user.server.model.js. Give that a try. – JohnnyHK May 05 '16 at 17:48
  • Thank you @JohnnyHK, that worked :) please post your comment in answers section so that I can mark it as an answer. – Dinu May 05 '16 at 17:52
  • @JohnnyHK may I know why exports.User doesn't work here? – Dinu May 05 '16 at 18:02
  • Because that creates a `User` property on the object returned from the `require` call. So you would need to change your `require` call to the following for that to work: `User = require('../models/user.server.model').User` – JohnnyHK May 05 '16 at 18:04

1 Answers1

1

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;
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471