'Mongoose save() does not work on all models
I am using Nodejs, Express and Mongoose to store data. I have 2 Models: Contact and Shop. My contact schema works, it sends data to my db. But Shop simply won't and I am pulling out my hair, not understanding why. Currently I am trying to hard code the data to just get it saved to the db. The database is connected, because the Contact model sends data with no problem.
In MongoDB I have a collection called "shops" and I want to insert the data in there.
My Shop Model:
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;
My shop router:
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;
My app.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.Promise = global.Promise;
const db = 'mongodb+srv://user:[email protected]/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);
I don't know what I am missing. I compared everything to my Contact model that works, and there is also no error. I checked that I am connected to the database and I am.
Solution 1:[1]
You have define '/add-shop' routes for your POST request simple way to fix this error is to remove () brackets that you have defined before your '/add-shop' routes so, code will look like this.
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));
});
Hope this helps!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kedar sedai |
