我在猫鼬中使用“创建”变得不确定

时间:2019-08-11 15:10:03

标签: node.js mongodb mongoose

我正在尝试将简单的json数据保存到数据库中。当我尝试通过Mongoose.create保存数据时,出现未定义的错误

App.js

import express from 'express';
import {router} from './config/routes';
import mongoose from 'mongoose';
import logger from 'morgan';

mongoose.Promise = global.Promise;
//mongoose.connect('mongodb://localhost:27017/invoice-builder');
 mongoose.connect('mongodb://localhost:27017/invoice-builder', { useNewUrlParser: true }, function(err) { console.log("mongoDB connected", err); }) ;

// const uri = 'mongodb://localhost:27017/test?poolSize=4';
// mongoose.createConnection(uri);

const app = express();
const PORT = 3000;

app.use(express.json());
app.use(express.urlencoded());

app.use(logger('dev'));

app.use('/api', router);

app.use((req, res, next) => {
....
...

这是我的控制器:

import { Invoice } from '../models/invoice.model'

const invoices = [
    {_id: '1123', item: 'Am Prod', qty: 1, date: new Date()},
    {_id: '1124', item: 'Am Prod 1', qty: 2, date: new Date()},
    {_id: '1125', item: 'Am Prod 2', qty: 3, date: new Date()}
  ];


export default {
    findAll(req, res, next){
        // res.json(invoices);
        Invoice.find().then(invoices => res.json(invoices));
    },

    create(req, res){

        const {item, qty, date, due, tax, rate} = req.body;

        if(!item){
          return  res.status(400).json({err: 'item is required'});
        }

        if(!date){
            return  res.status(400).json({err: 'date is required'});
        }
        if(!due){
            return  res.status(400).json({err: 'due is required'});
        }

        if(!qty){
            return  res.status(400).json({err: 'qty is required'});
        }

        Invoice.create({item, qty, date, due, tax, rate})
        .then(invoice => res.json(invoice))
        .catch(err => res.status(500).json(err));
    }
};

这是我的输入内容

{
    "item" : "This is temp",
    "date" : "2019-01-01",
    "due" : "2019-03-03",
    "qty" : 1
}

这是我得到的错误:

{
    "error": {
        "message": "Cannot read property 'create' of undefined"
    }
}

请帮助我在此处查找问题。我尝试了在stackoverflow或其他站点中提供的许多解决方案。但是它们都没有帮助。

1 个答案:

答案 0 :(得分:0)

您收到错误消息,因为调用Invoice.create函数时Invoice变量未定义。您必须先初始化发票。

类似的东西:

var invoice = new Invoice();  //put it somewhere out of the create method
...
invoice.create({item, qty, date, due, tax, rate}) //use the object, not the class