Search code examples
node.jsmongodbmongoosemongoose-schema

Creating Mongoose Model takes indefinite amount of time


I tried creating a simple Mongoose schema, and then a corresponding route to handle saving of restaurant models.

//models/Restaurant.js

import mongoose from 'mongoose';

const restaurantSchema = new mongoose.Schema({
    name: String,
    description: String,
});

export default mongoose.model('Restaurant', restaurantSchema);

// routes/restaurants.js

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

const Restaurant = require('../models/Restaurant')

router.post('/', async (req, res) => {
    try {
        const { name, description } = req.body
        let restaurant = new Restaurant({name, description}) 
console.log(restaurant)
// does not print anything to the console and the program stops here for an indefinite amount of time.
        restaurant = await restaurant.save()
        res.status(200)
        res.json(restaurant)


    } catch (err) {
        res.status(500)
    }
})

module.exports = router;

Why does the program stop at creating restaurants for an indefinite amount of time? Is there something wrong with the way I setup my mongoose schemas/model/or the way I create a new model?

Thank you in advance!


Solution

  • That is because you confuse ES6 and CommonJS modules.

    Don't confuse ES6 and CommonJS. Choose one or the other. In this code sample, I'll revise your model with CommonJS style of writing. Node.js uses CommonJS by default, but I believe it can be changed.

    const mongoose = require('mongoose');
    
    const restaurantSchema = new mongoose.Schema({
        name: String,
        description: String,
    });
    
    const Restaurant = mongoose.model('Restaurant', restaurantSchema);
    
    module.exports = Restaurant;