如何在复杂的mongoDb模式中发布到嵌套字段

阿尔伯特·阿塔科拉·弗里蓬:

我有一个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;

我也有一个Express Server 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]": "[email protected]",
    "phonenumbers[homephone]": ["alb"],
    "phonenumbers[workphone]": ["031"],
    "phonenumbers[cellphone]": ["02098767865"]
}

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

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

请我缺少什么。是堆栈。

穆罕默德·尤斯里(Mohammed Yousry):

您正在以错误的格式发送数据,而邮递员

"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部分,关于您的请求,我认为您应该以邮递员的这种格式传递数据

{
    "userid": "hi",
    "userinfo": {
        "First_Name": "Albert",
        "Last_Name": "Attakora",
        "Current_Address": "Kumasi",
        "Email_Address": "[email protected]"
    },
    "phonenumbers": [{
        "Home_Phone": "alb",
        "Work_Phone": "031",
        "Cell_Phone": "02098767865"
    }]
}

请注意,架构仅包含三个字段: UserID, User_Info, Phone_Numbers

User_Info是一个包含的对象First_Name, Last_Name, ..,因此First_Name架构中没有调用任何属性,它应该是User_Info.First_Name

同样,Phone_Numbers是一个对象数组,每个对象都有Home_Phone, Work_Phone, ...,因此在架构中没有所谓的Home_phoneWork_Phone

通过提供给邮递员的JSON,我们遵循的是架构,因此我们可以在 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 });
    }
});

更新资料

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

我建议您执行以下操作

传递给邮递员的数据应该是这样的

{
    "userid": "hi",
    "firstname": "Albert",
    "lastname": "Attakora",
    "currentaddress": "Kumasi",
    "emailaddress": "[email protected]",
    "homephone": "alb",
    "workphone": "031",
    "cellphone": "02098767865"
}

在发布路线中,我们可以执行以下操作

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 });
    }
});

希望能帮助到你

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章