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

Node.js 如何发布到复杂mongoDb模式中的嵌套字段,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我有一个mongoDb模式,我想向它发出post请求,但我遇到了一些问题。 下面是在我的应用程序的根目录中找到的模型文件夹中的架构 const mongoose = require('mongoose'); let Schema = mongoose.Schema; const userSchema = new Schema({ UserID: { type: mongoose.Schema.Types.Mixed, }, User_Info: { First_Name:

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

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

当我试着用邮递员发邮件请求时,如下所示

{
    "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
    }
]

请告诉我我错过了什么。Am stack.

我想你是在邮递员以错误的格式发送数据

"userinfo[firstname]": "Albert" // here, userinfo is not defined as an object
如果你需要使用这种格式,它应该是方括号内的一个字符串,如果你没有,那么你会得到一个错误,没有定义firstname

对于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\u Info、Phone\u number

User\u Info
是一个包含
First\u Name、Last\u Name、…
的对象,因此架构中没有名为
First\u Name
的属性,它应该是
User\u Info.First\u Name

另外,
Phone\u Numbers
是一个对象数组,每个对象都有
Home\u Phone、Work\u Phone、
,因此架构中没有名为
Home\u Phone
Work\u Phone

通过提供给postman的这个JSON,我们遵循的是模式,因此我们可以在
post路径中使用以下代码

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

更新 如果您无法控制字段名,因为它们来自客户端,那么您可以只发送模式中每个属性的详细信息,然后在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 });
    }
});
传递给邮递员的数据应该是这样的

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

希望它有帮助

您好,谢谢,它很有效,我非常感谢您的回复,但您知道我的目标是能够从html表单发出post请求。我应该如何命名输入字段。这是我现在尝试过的,但没有成功userid:firstname:send`我已经更新了我的答案,你能再检查一下吗?',你也可以在html中更改变量名,你可以将名字字段命名为“firstname”而不是“userinfo[firstname]”,等等,所有其他字段都是这样的“firstname”,“lastname”。。。属性将被发送到post请求,因此我们可以像我在更新的答案中所做的那样将它们插入db,希望它能帮助您,正如您所解释的那样,它工作得非常完美。再次感谢各位,如有任何需要,我将联系intouch进行澄清。继续我的项目,干杯。很高兴帮助您:)