postman 0我正在处理NodeJs应用程序它的商店应用程序,我正在尝试将帖子保存在数据库中,但提交表单后出现此错误:

jgovgodb  于 2023-01-30  发布在  Postman
关注(0)|答案(1)|浏览(107)

TypeError:Post不是构造函数
owoce.js

const express = require('express');

const router = express.Router();
const Post = require('../models/owoc');

router.get('/',  (req,res) => {
    res.send('we are on owoce');
    //try {
    //    const owoce = await Owoc.find()
    //    res.json(owoce)
        
   // }catch (err){

    
       // res.status(500).json({ message: err.message })
        
   // }
        
 })

// router.get('/jablka', (req,res) => {
 //   res.send('we are on jablka');
 //});

 router.post('/', (req,res) => {
    const owoc = new Post({
        rodzaj: req.body.rodzaj,
        kolor: req.body.kolor
    })

    owoc.save()
    .then(data =>{
        res.json(data);
    })
    .catch(err => {
        res.json({message: err});
    });
 });

 module.exports = router;

owoc.js它包含模式

const mongoose = require('mongoose');

const OwocSchema = new mongoose.Schema({
    rodzaj: {
        type: String,
        required: true
    },
    kolor: {
        type: String,
        required: true 
    },
    date: {
        type: Date,
        default: Date.now
    }
});

//mongoose.Schema({
 //   username: String,
  //  password: String

//})

mongoose.exports = mongoose.model('Owoc', OwocSchema)

我不知道是什么问题后,看simmilar anwseres在这里,我不知道什么应该改变const Post = require('../models/owoc');
server.js添加它,因为它可能有助于故障排除

const express = require('express')
//const req = require('express/lib/request');
//const res = require('express/lib/response');
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser');
require('dotenv/config');

app.use(bodyParser.json());

//const db = mongoose.connection('mongodb://localhost/sklep')
//MIDDLEWARES
app.use('/posts', ()=> {
    console.log('This is a middleware');
});

//IMPORT ROUTES
const owoceRoute = require('./routes/owoce');

app.use('/owoce', owoceRoute);

//ROUTES
app.get('/', (req,res) => {
   res.send('we are on home');
});



//connect to DB
mongoose.connect(
    process.env.DB_CONNECTION ,mongoose.set('strictQuery', true),  ()=> {
    console.log('Connected to DB!!:))');
}); //{ useNewUrlParser: true})




//how to lisen to server
///db.on('error',(error) => console.error(error))
///db.once('open',() => console.log('connected to database'))
//db.on('connected', () => console.log('Connected to database'))
app.listen(3000, () => console.log('server started'))

我正在添加截图和服务器代码应用程序,尽管不确定它是否会有任何帮助
here is the screen from Postman

b4wnujal

b4wnujal1#

试试这个:

router.post('/create', async (req,res) => {
    const owoc = await Owoc.create({
        rodzaj: req.body.rodzaj,
        kolor: req.body.kolor
    })
    .then(data =>{
        res.json(data);
    })
    .catch(err => {
        res.json({message: err});
    });
 });

相关问题