当我在Postman中检查post json数据时,“TypeError:Contact不是构造函数”

问题描述 投票:0回答:1

当我运行节点app.js它工作,并没有给出任何错误。但是,当我路由localhost:3000 / api / contact并发布json以通过Postman检查时,它会给出错误。我已经看到了一些其他问题,但无法确定。这是我的app.js

//importing modules

var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');

var app = express();

const route = require('./routes/route');

//connect to mongodb
mongoose.connect('mongodb://localhost:27017/contactlist');

//connection on
mongoose.connection.on('connected',()=>{
    console.log('Database connected');
});

mongoose.connection.on('error',(err)=>{
    if(err)
    {
        console.log('Error in database'+err);
    }
});

//path port
const port = 3000;

//adding middleware
app.use(cors());

//body-parser
app.use(bodyparser.json());

//static path
app.use(express.static(path.join(__dirname,'public')));
//add route
app.use('/api',route);

//testing server
app.get('/',(req,res)=>{
    res.send('foobar');
});

app.listen(port,()=>{
     console.log('server is started at port:'+port);
});

这是我的route.js

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


const Contact = require('../models/contacts');

//get data
router.get('/contacts', (req, res, next)=>{
    Contact.find(function(err, contacts){
        res.json(contacts);
    });
});

//add data
router.post('/contact',(req, res, next)=>{
    let newContact = new Contact({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        phone_num: req.body.phone_num 
    });

    newContact.save((err, contact)=>{
        if(err)
        {
            res.json({msg: 'Failed to add contact'});
        }
        else
        {
            res.json({msg: 'Contact add succesfuly'});;
        }
    });
});

//delete data
router.delete('/contact/:id', (req, res, next)=>{
    Contact.remove({_id: req.params.id}, function(err, result){
        if(err)
        {
            res.json(err);
        }
        else
        {
            res.json(result);
        }
    });
});
module.exports = router;

我是一个新的节点js学习者。我不明白有什么问题请帮帮我。提前致谢!

angularjs node.js mongodb express
1个回答
0
投票

看看下面的代码:

// your schema and model
// should look similar to below
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var ContactSchema = new Schema({
    first_name: String,
    last_name: String,
    phone_num: String
});

const Contact = mongoose.model('Contact', ContactSchema);
module.exports =  Contact;

也许你忘了使用mongoose.model

© www.soinside.com 2019 - 2024. All rights reserved.