Mongodb不保存数据

时间:2019-11-30 15:10:05

标签: javascript node.js mongodb mongoose

我正在使用mongodb创建CRUD,并且不会引发错误,但是当我尝试插入数据时,不会插入数据。有人帮我

App.js

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

const app = express();

// connecting to db
mongoose.connect('mongodb://localhost/crud', { useUnifiedTopology: true, useNewUrlParser: true })
.then(db => console.log('DB connected'))
.catch(err => console.log(err));

// importing routes
const indexRoutes = require('./routes/index');

// settings
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');  

// middlewares
app.use(morgan('dev'));
app.use(express.urlencoded({extended: false}));

// routes
app.use('/', indexRoutes);

// starting the server
app.listen(app.get('port'), () => {
    console.log(`Server on port ${app.get('port')}`);
});

index.js

const express = require('express');
const router = express.Router();
const Task = require('../models/task');

router.get('/', async (req, res) => {
  const tasks = await Task.find();
  res.render('index', {
    tasks
  });
});

router.post('/add', async (req, res, next) => {
  const task = new Task(req.body);
  console.log(req.body)
  await task.save();
  res.redirect('/');
})

module.exports = router;

task.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const TaskSchema = Schema({
    CLiente: String ,
    Correo: String ,
    Direccion: String ,
    Telefono: Number 
});

module.exports = mongoose.model('tasks', TaskSchema);

2 个答案:

答案 0 :(得分:0)

在task.js中,您犯了一些小错误,请初始化Schema,然后将其分配给TaskSchema。

  const mongoose = require('mongoose');
  const Schema = mongoose.Schema;

  const TaskSchema = new Schema({
      CLiente: String ,
      Correo: String ,
      Direccion: String ,
      Telefono: Number 
  });

  module.exports = mongoose.model('tasks', TaskSchema);

答案 1 :(得分:0)

要能够从请求正文中进行读取,您需要在使用路由之前添加app.use(express.json());

因此,像这样更改您的App.js代码:

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

const app = express();

// connecting to db
mongoose.connect('mongodb://localhost/crud', { useUnifiedTopology: true, useNewUrlParser: true })
.then(db => console.log('DB connected'))
.catch(err => console.log(err));

// importing routes
const indexRoutes = require('./routes/index');

// settings
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');  

// middlewares
app.use(morgan('dev'));

app.use(express.json());
app.use(express.urlencoded({extended: false}));

// routes
app.use('/', indexRoutes);

// starting the server
app.listen(app.get('port'), () => {
    console.log(`Server on port ${app.get('port')}`);
});

还要确保请求主体中的字段名称必须与任务模型中的名称相同,因为您是直接使用req.body创建任务的。