节点js控制器如何为对象数组保存数据

时间:2019-03-29 17:55:01

标签: node.js mongoose mongoose-schema

const mongoose = require('mongoose');

const addressSchema = mongoose.Schema({
    type: String,
    street: String,
    city: String,
    state: String,
    country: String,
    postalcode: Number

});


const createStudentSchema = mongoose.Schema({
    admisionnum: Number,
    first: String,
    last: String,
    phone: String,
    address : [addressSchema],
    isActive : { type : Boolean, default: true}

}, {
    timestamps: true
});

module.exports = mongoose.model('createStudent', createStudentSchema);

Addreschema表示对象数组中的地址。我在下面的json的输出中得到null。

这是json输入

{
    "admisionnum":"1",
    "first": "Dan",
    "last": "HEllo",
    "phone": "9000909575",
    "address" : [
        {
            "type": "own",
            "street": "18 ksdhks",
            "city": "chennai",
            "state": "Tamil Nadhu",
            "country": "India",
            "postalcode": "600097"
        }
        ],
        "isActive": "true"
}

Response Json输出

{
    "isActive": true,
    "_id": "5c9e57f718e3de2ca4dd1d86",
    "admisionnum": 1,
    "first": "Jesus",
    "last": "christ",
    "phone": "9000909575",
    "address": [
        null,
        null,
        null,
        null,
        null,
        null
    ],
    "createdAt": "2019-03-29T17:37:59.291Z",
    "updatedAt": "2019-03-29T17:37:59.291Z",
    "__v": 0
}

请帮助您为地址绑定数据。控制器代码低于

exports.createStudent = (req, res) => {


    // Create a Note
    const CreateStudent = new createStudent({
        admisionnum: req.body.admisionnum,
        first: req.body.first,
        last: req.body.last,
        phone: req.body.phone,
        address : [

            req.body.address.type,
            req.body.address.street,
            req.body.address.city,
            req.body.address.state,
            req.body.address.country,
            req.body.address.postalcode

        ] ,
        isActive: req.body.type


    });

    // Save Note in the database
    CreateStudent.save()
    .then(data => {
        res.send(data);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Some error occurred while creating the Note."
        });
    });
};

1 个答案:

答案 0 :(得分:0)

只需使用address : req.body.address,它就可以正常工作。

由于您的address是一个数组,并且您也在address中发送request数组,因此您无需执行其他任何操作。

尝试一下:

const CreateStudent = new createStudent({
    admisionnum: req.body.admisionnum,
    first: req.body.first,
    last: req.body.last,
    phone: req.body.phone,
    address : req.body.address ,
    isActive: req.body.type


});