无法使用快速框架创建然后将数据保存到mongo db(现在工作。)

时间:2018-02-15 07:47:48

标签: node.js mongodb express mongoose body-parser

以下是我的代码,如果我从数据库中找到它,但它在create方法中只能将数据保存到数据库中,它运行良好

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();


// create application/json parser
app.use(bodyParser.json())

// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }))

mongoose.connect('mongodb://localhost/quicks');
const db = mongoose.connection;

const userSchema = mongoose.Schema({
    name: String
});
const User = mongoose.model('user', userSchema);


app.get('/', (req, res) => res.send('Hello World!'))

app.post('/createuser', (req, res) => {
    let value = {
        name : req.body.Name,
        email : req.body.Email,
        password : req.body.Password
    };
    User.create(value)
    .then((records) => {return res.json(records)})
    .catch((err) => {return res.json("err")})
})


app.post('/user', (req, res) => {
    let value = {
        _id : req.body.ID
    };
    user.findOne(value)
    .then((records) => {return res.json(records)})
    .catch((err) => {return res.json("err")})
})


app.listen(4000, () => console.log('Example app listening on port 4000!'))

我无法获取我创建的数据。仅创建ID。什么是可能的错误?

1 个答案:

答案 0 :(得分:1)

在您的架构中,电子邮件和密码字段丢失。

试试这个,

app.post('/createuser', (req, res) => {
    let value = {
        name: req.body.Name,
        email: req.body.Email,
        password: req.body.Password
    };
    let model = new User();
    model = Object.assign(model, value);
    model.save()
        .then((records) => {
            return res.json(records)
        })
        .catch((err) => {
            return res.json("err")
        })
})