创建 Mongoose 模型需要无限长的时间

Creating Mongoose Model takes indefinite amount of time

我尝试创建一个简单的 Mongoose 模式,然后创建一个相应的路由来处理餐厅模型的保存。

//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;

为什么程序会无限期地停止创建餐厅?我设置猫鼬的方式有问题吗 schemas/model/or 我创建新模型的方式?

提前致谢!

那是因为你混淆了 ES6 和 CommonJS 模块。

不要混淆 ES6 和 CommonJS。选择一个或另一个。在此代码示例中,我将使用 CommonJS 的写作风格修改您的模型。 Node.js 默认使用 CommonJS,但我相信它可以更改。

const mongoose = require('mongoose');

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

const Restaurant = mongoose.model('Restaurant', restaurantSchema);

module.exports = Restaurant;

在 console.log() 之前你需要调用保存方法

let restaurant = new Restaurant({name, description});
restaurant = await restaurant.save();