Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Movie is not a constructor - Mongoose

Tags:

I'm using the MEAN stack and trying to save data to my MongoDB database with Mongoose. However, I keep getting the error "Movie is not a constructor" for my model. But this is how the Mongoose docs show it, so i'm not sure what i'm doing wrong..

Please help!

Movie.js

let mongoose = require('mongoose');

let MovieSchema = new mongoose.Schema({
    title: String,
    genre: String
});

export let Movie = mongoose.model("Movie", MovieSchema);

route.js

import express = require('express');
import mongoose = require('mongoose');
let Movie = require('../models/Movie');
let router = express.Router();

router.post('/movies', function(req, res, next) {
  let new_movie = new Movie(req.body);
  new_movie.save(function(err, movie) {
    if(err) return next(err);
    res.send(movie);
  });
});
like image 492
Isaac G. Avatar asked Aug 06 '16 18:08

Isaac G.


1 Answers

This problem happens when you forget to export your model from the model file or exports in a wrong way. your model should export like this:

let Movie = mongoose.model("Movie", MovieSchema);
module.exports=Movie;

Or in a shorthand you can simply write:

module.exports=mongoose.model('Movie',MovieSchema);
like image 157
Mostafa Darezereshki Avatar answered Sep 23 '22 16:09

Mostafa Darezereshki