繁体   English   中英

如何发布到复杂 mongoDb 架构中的嵌套字段

[英]How do I post to a nested field in a complex mongoDb schema

我有一个 mongoDb 架构,我想向它发出发布请求,但我遇到了一些问题。 下面是在我的应用程序根目录中找到的 model 文件夹中的架构。

const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const userSchema = new Schema({
UserID: {
    type: mongoose.Schema.Types.Mixed,
  },
  User_Info: {
    First_Name: {
      type: String,
    },
    Last_Name: {
      type: String,
    },
    Current_Address: {
      type: String,
    },
    Email_Address: {
      type: String,
    },
  },
      Phone_Numbers: [{
        Home_Phone: {
          type: Number,
        },
        Work_Phone: {
          type: Number,
        },
        Cell_Phone: {
          type: Number,
        },
            Phone_verified: [{
              Home: Boolean,
              Work: Boolean,
              Cell: Boolean,
            }],
      }],
})
const User = mongoose.model('User', userSchema);
module.exports = User;

我还有一个快递服务器 api 如下

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

    router.get('/', async (req, res) => {
        try{
            const complexposts = await ComplexPost.find().sort({date:-1});
                res.json(complexposts);
        }   catch(err){
                res.json({message: err});
        }
    });

  router.post('/', async (req, res) => {
    ComplexPost.create({
        UserID: req.body.userid,
        User_Info: req.body.userinfo,
        First_Name: req.body.firstname,
        Last_Name: req.body.lastname,
        Current_Address: req.body.currentaddress,
        Email_Address: req.body.emailaddress,
        Phone_Numbers: req.body.phonenumbers,
        Home_Phone: req.body.homephone,
        Work_Phone: req.body.workphone,
        Cell_Phone: req.body.cellphone,
        Phone_Verified:req.body.phoneverified,
        Home: req.body.home,
        Work: req.body.work,
        Cell: req.body.cell,
    });
    try{
    await ComplexPost.save()
    res.redirect('/');
    }catch(err){
        res.json({message: err});
    }
});

module.exports = router;

在我的index.js文件中,我有以下代码;

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

// Middlewares
require('dotenv/config');
app.use(cors());
app.use(bodyParser.json());

// Body Parser Middleware 
app.use(express.json());
app.use(express.urlencoded({ extended: false}));

app.use(bodyParser.urlencoded({
    extended: true
  }));

// Import routes
const complexRoute = require('./server/complexPost');
app.use('/complex', complexRoute);

// Serving static folder
app.use(express.static(path.join(__dirname, 'public'))); 

// Connect to DB
mongoose.connect( 
    process.env.DB_CONNECTION, 
    {  useNewUrlParser: true ,
       useUnifiedTopology: true, 
    },
    () => console.log('Connected to DB')
);

const port = process.env.PORT || 1100;
app.listen(port, () => console.log(`server started on port ${port}`));

当我尝试使用 Postman 如下发出发布请求时;

{
    "userid": "hi",
    "userinfo[firstname]": "Albert",
    "userinfo[lastname]": "Attakora",
    "userinfo[currentaddress]": "Kumasi",
    "userinfo[emailaddress]": "Kum@gmail.com",
    "phonenumbers[homephone]": ["alb"],
    "phonenumbers[workphone]": ["031"],
    "phonenumbers[cellphone]": ["02098767865"]
}

我得到了没有用户信息和电话号码详细信息的结果

[
    {
        "_id": "5eca8b45feeb163e7cc46662",
        "UserID": "hi",
        "Phone_Numbers": [],
        "__v": 0
    }
]

请问我错过了什么。 我是堆栈。

我猜你在 postman 格式错误时发送数据

"userinfo[firstname]": "Albert" // here, userinfo is not defined as an object

另外,如果你需要使用这种格式,它应该是方括号内的字符串,如果你不这样做,那么你会得到一个错误,即未定义名字,

对于 javascript 你可以像这样使用它

"userinfo['firstname']": "Albert", // this is a side note, for javascript only

或使用像这样的点符号"userinfo.firstname": "Albert"

这是 javaScript 部分,关于您的请求,我认为您应该在 postman 中以这种格式传递数据

{
    "userid": "hi",
    "userinfo": {
        "First_Name": "Albert",
        "Last_Name": "Attakora",
        "Current_Address": "Kumasi",
        "Email_Address": "Kum@gmail.com"
    },
    "phonenumbers": [{
        "Home_Phone": "alb",
        "Work_Phone": "031",
        "Cell_Phone": "02098767865"
    }]
}

请注意,该架构只有三个字段: UserID, User_Info, Phone_Numbers

User_Info是一个 object 包含First_Name, Last_Name, .. ,所以架构中没有名为First_Name的属性,它应该是User_Info.First_Name

此外, Phone_Numbers是一个对象数组,每个 object 都有Home_Phone, Work_Phone, ... ,因此在名为Home_phoneWork_Phone的模式中没有任何内容

通过这个 JSON 提供给 postman ,我们遵循架构,所以我们可以在post route中使用以下代码

router.post('/', async (req, res) => {
    ComplexPost.create({
        // just define the required three fields in the schema, UserID, User_Info, Phone_Numbers
        UserID: req.body.userid,
        User_Info: req.body.userinfo, // req.body.userinfo now has the full info (First_Name, Last_Name, ... ) with the same names as defined in the schema, so we can use the object directly
        Phone_Numbers: req.body.phonenumbers, // req.body.phonenumbers now has the full info about the phones, with the same names as defined in the schema


        // all the following do not exist in the schema

        // First_Name: req.body.firstname,
        // Last_Name: req.body.lastname,
        // Current_Address: req.body.currentaddress,
        // Email_Address: req.body.emailaddress,
        // Home_Phone: req.body.homephone,
        // Work_Phone: req.body.workphone,
        // Cell_Phone: req.body.cellphone,
        // Phone_Verified: req.body.phoneverified,
        // Home: req.body.home,
        // Work: req.body.work,
        // Cell: req.body.cell,
    });
    try {
        await ComplexPost.save()
        res.redirect('/');
    } catch (err) {
        res.json({ message: err });
    }
});

更新

如果您无法控制来自客户端的字段名称,那么您可以发送模式中每个属性的详细信息,然后在发布路由中我们可以分配它们,

我建议您执行以下操作

传递给 postman 的数据应该是这样的

{
    "userid": "hi",
    "firstname": "Albert",
    "lastname": "Attakora",
    "currentaddress": "Kumasi",
    "emailaddress": "Kum@gmail.com",
    "homephone": "alb",
    "workphone": "031",
    "cellphone": "02098767865"
}

在 post 路由中,我们可以执行以下操作

router.post('/', async (req, res) => {
    ComplexPost.create({
        UserID: req.body.userid,

        // User_Info: req.body.userinfo, // no userinfo in the req.body now, we will create it here in the post request
        User_Info: {
            First_Name: req.body.firstname,
            Last_Name: req.body.lastname,
            Current_Address: req.body.currentaddress,
            Email_Address: req.body.emailaddress,
        },


        // Phone_Numbers: req.body.phonenumbers, // no phonenumbers in req.body
        Phone_Numbers: [{
            Home_Phone: req.body.homephone,
            Work_Phone: req.body.workphone,
            Cell_Phone: req.body.cellphone,
        }],

    });
    try {
        await ComplexPost.save()
        res.redirect('/');
    } catch (err) {
        res.json({ message: err });
    }
});

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM