猫鼬save()不适用于所有型号

时间:2020-07-03 11:27:17

标签: node.js express mongoose

我正在使用Nodejs,Express和Mongoose存储数据。我有2个模型:Contact和Shop。我的联系模式有效,它将数据发送到我的数据库。但是Shop根本不会,我正在拔头发,不明白为什么。目前,我正在尝试对数据进行硬编码,以将其保存到数据库中。数据库已连接,因为Contact模型可以毫无问题地发送数据。

在MongoDB中,我有一个名为“商店”的集合,我想在其中插入数据。

我的商店型号:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ShopSchema = new Schema({
    shopName: {
        type: String,
        required: true
    },
    shopImage: {
        type: String,
        required: true
    },
    shopDescription: {
        type: String,
        required: true
    },
    shopCategory: {
        type: String,
        required: true
    },
}, { timestamps:true });

const Shop = mongoose.model('Shop', ShopSchema);
module.exports = Shop;

我的商店路由器:

const express = require('express');
const router = express.Router();
const Shop = require('../models/shopModel.js');

router.get('/add-shop', (req, res) => {
    ShopCategory.find()
        .then(result => res.render('shop/add-shop', { title: "Add a Shop" }))
        .catch(err => console.log(err));
});

router.post(('/add-shop', (req, res) => {
    const shop = new Shop({
        shopName: "A shop name",
        shopImage: '88.jpg',
        shopDescription: 'This is a description',
        shopCategory: "Food"
    });
    shop.save()
        .then(result => console.log(result))
        .catch(err => console.log(err));
}));

module.exports = router;

我的app.js


const express = require('express');
const mongoose = require('mongoose');

const app = express();

mongoose.Promise = global.Promise;
const db = 'mongodb+srv://user:pass@nodetuts-6iczn.mongodb.net/shop?retryWrites=true&w=majority';

mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(result => app.listen(3000))
    .catch(err => console.log(err));

const shopRoutes = require('./routes/shop.js');
app.use(shopRoutes);

我不知道我在想什么。我将所有内容与有效的Contact模型进行了比较,并且也没有错误。我检查了我是否已连接到数据库。

1 个答案:

答案 0 :(得分:0)

您已经为'/add-shop'请求定义了POST路由解决此错误的简单方法是,在()路由之前删除您定义的'/add-shop'括号,因此,代码会像这样。

router.post('/add-shop', (req, res) => {
    const shop = new Shop({
        shopName: "A shop name",
        shopImage: '88.jpg',
        shopDescription: 'This is a description',
        shopCategory: "Food"
    });
    shop.save()
        .then(result => console.log(result))
        .catch(err => console.log(err));
});

希望这会有所帮助!