【问题标题】:Why won't my rest api post request save my array in my mongodb database为什么我的rest api post请求不能将我的数组保存在我的mongodb数据库中
【发布时间】:2019-01-18 11:42:27
【问题描述】:

我正在尝试学习使用 node.js 制作一个 api 对于我的后端,我使用的是 mongodb,我使用的是 mongoose 作为 ORM。我按如下方式创建了我的用户模型。

// User.js
var mongoose = require('mongoose');  
var UserInfoSchema = new mongoose.Schema({  
    street: String,
    housenumber: String,
    city: String,
    postcode: String,
    bus: String,
  });
var UserFullSchema = new mongoose.Schema({  
  name: String,
  email: String,
  password: String,
  Userinfo: [UserInfoSchema]
});


mongoose.model('User', UserFullSchema);

const User = mongoose.model('user',UserFullSchema)
module.exports = User;

我的用户控制器如下所示:

// UserController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
var User = require('./User');
// CREATES A NEW USER




router.post('/', function (req, res) {
    User.create({
        name : req.body.name,
        email : req.body.email,
        password : req.body.password,
        Userinfo: [{
            street : req.body.street,
            housenumber : req.housenumber,
            city : req.body.city,
            postcode : req.body.postcode,
            bus : req.body.bus,
        }]
    }, 
        function (err, user) {
            if (err) return res.status(500).send("There was a problem adding the information to the database.");
            res.status(200).send(user);
        });
});

由于某种原因,当我使用邮递员调用我的 API 进行测试时,我永远看不到能够填充我的数组。我是不是做错了什么?

以图片为例:

我在发布前检查过的页面: Page I checked

【问题讨论】:

    标签: node.js mongodb express mongoose postman


    【解决方案1】:

    您希望通过_id 进行交叉引用的定义似乎已关闭。

    Userinfo: [UserInfoSchema]
    

    应该是:

    Userinfo: [{ type: mongoose.Schema.Types.ObjectId, ref:  'UserInfoSchema' }]
    

    这样您将获得_id 的交叉引用。顺便说一句,不喜欢这些名字。读起来非常混乱。我认为这些只是为了测试。

    【讨论】:

    • 更改用户信息无效。现在我收到消息“将信息添加到数据库时出现问题。”在邮递员。是的,这些名称仅用于测试。
    • 这是第一步。下一个是查看您的.create 并更改它,因为您无法像这样添加。您必须首先为UserInfoSchema 创建模型,然后将其_id 添加为User.create UserInfo 的一部分。您正在与您的帖子一起发送一个 _id 并以某种方式进入价值? IT 不能以这种方式工作。阅读:mongoosejs.com/docs/populate.html
    【解决方案2】:

    现在,从简单的express 角度来看,您甚至引用了 req.body 中的值吗? 值不应该是req.body.Userinfo.street 吗?

    Userinfo: [{
            street : req.body.Userinfo.street, // 
            housenumber : req.body.Userinfo.housenumber,
            city : req.body.Userinfo.city,
            postcode : req.body.Userinfo.postcode,
            bus : req.body.Userinfo.bus,
        }]
    

    附带说明,您可以使用邮递员发送完整的 JSON,转到 raw 选项卡并从下拉列表中选择 application/json

    【讨论】:

    • 尝试按照您的建议进行更改,但结果仍然相同。我也尝试通过 JSON 发送,但是当我没有填充任何变量时,甚至没有填充用户变量。
    • 您能否通过控制台记录 req.body 并检查一切是否按预期进行?
    • 正文:{名称:'Pedro Lopes',电子邮件:'pedro@hotmail.com',密码:'789852123',用户信息:{ street:'street'}},_body:真,长度:未定义,阅读:[功能],路线:路线{路径:'/',堆栈:[[对象]],方法:{帖子:真}}}
    • 所以问题不在于邮递员的请求,而是我如何将用户保存到数据库
    【解决方案3】:

    我不知道问题出在哪里,但我能够通过将模型拆分为 2 个不同的文件来解决问题。 我创建了一个名为 Userinfo 的新文件,如下所示:

    // Userinfo.js
    var mongoose = require('mongoose');  
    var UserInfoSchema = new mongoose.Schema({
        street: String,
        housenumber: String,
        city: String,
        postcode: String,
        bus: String,
      });
    
    module.exports = UserInfoSchema;
    

    在那里我导出了我的整个架构

    并在我的用户模型文件中调用该架构,如下所示:

    // User.js
    
    var Userinfo = require('../userinfo/Userinfo.js');
    var mongoose = require('mongoose');  
    var UserFullSchema = new mongoose.Schema({  
      name: String,
      email: String,
      password: String,
      Userinfo: [Userinfo]
    });
    
    const User = mongoose.model('user',UserFullSchema)
    module.exports = User;
    

    我的控制器看起来像这样:

    // UserController.js
    var express = require('express');
    var mongoose = require('mongoose');
    var router = express.Router();
    var bodyParser = require('body-parser');
    router.use(bodyParser.urlencoded({ extended: true }));
    var User = require('./User');
    
    
    router.post('/', function (req, res) {
        User.create({
            name : req.body.name,
            email : req.body.email,
            password : req.body.password,
            Userinfo: [{
                street : req.body.Userinfo.street,
                housenumber : req.body.Userinfo.housenumber,
                city : req.body.Userinfo.city,
                postcode : req.body.Userinfo.postcode,
                bus : req.body.Userinfo.bus,
            }]
        }, 
            function (err, user) {
                if (err) return res.status(500).send("There was a problem adding the information to the database.");
                res.status(200).send(user);
                console.log(req);
            });
    });
    

    之后我像以前一样使用邮递员,瞧问题解决了:

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2012-07-05
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      相关资源
      最近更新 更多