javascript - 如何使用 node.js 中的循环将表单数据作为对象和对象数组保存到 mongodb?

标签 javascript node.js mongodb express mongoose

我是 MongoDB 的新手,我在我的项目中使用 Node.js、Express 4 和 mongoose(mongoDB)。我坚持在循环内将表单数据保存到 mongoDB,我的模型也包含对象和对象数组。

模型:

var Subscriber = new Schema({  
    first_name: String,  
    emergency_contact_1: {  
        name: String,  
        number: [{  
            type: String  
        }]  
    },  
    residential: {  
        phone: String,  
        address: String,  
        ...  
    },  
    medications: [  
    {  
        visit_id: { type: Object },  
        name: String,  
        ....  
    }],  
    food_allergies: [  
        {type: String}  
    ],  
    ....  
});  

Controller :
我想以这种方式保存数据:

var subscriber = new Subscriber();

//Here I am trying to save all form's fields to mongoBD fields.
for (var field in form_data) {
    subscriber[field] = form_data[field];
}

subscriber.save(function (err1, instance) {
    if (err) {
        console.log("error");
        return res.send("...");
    }
    console.log("saved successfully");
}

使用上面的循环可以正确保存普通字段,但是当对象或数组出现时,它不会保存到 mongoDB。

有什么解决办法吗?或任何其他方式通过循环插入/保存数据到 mongoDB 模型?
任何帮助将不胜感激。谢谢..!!

最佳答案

Node

var PersonSchema = new Schema({
    name: {
        given: {
            type: String,
            required: true
        },
        family: {
            type: String,
            required: true
        }
    },
    children: [PersonSchema]
});

var Person = mongoose.model('Person', PersonSchema);

app.post('/person', function (req, res) {
    Person.create(req.body)
        .then(function (created) {
            console.log(created);
            res.json(created.id);
        });
});

客户端

$.ajax({
    url: '/person',
    type: 'POST',
    data: {
        name: {
            family: 'Green'
        },
        children: [{
            name: {
                given: 'Matt',
                family: 'Green'
            }
        }, {
            name: {
                given: 'Dave',
                family: 'Green'
            }
        }]
    }
})

如您所见,我有嵌套的对象和数组。这对我来说很好:)

关于javascript - 如何使用 node.js 中的循环将表单数据作为对象和对象数组保存到 mongodb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26279422/

相关文章:

javascript - 变异观察者不起作用

javascript - MySQL 类型错误 : Cannot read property 'query' of undefined

javascript - TinyMCE 拼写检查器

javascript - 如何在 PhantomJS 中跟踪 document.location.reload?

mongodb - Spring数据mongo分页

mongodb - 为什么这个 msiexec.exe 命令在 powershell 中不起作用?

javascript - 鼠标悬停时堆栈图中的淡入淡出栏

node.js - nodejs Passport 身份验证 token

node.js - NodeJS/Express + HTTPS : How to deploy key & certificate to AWS EC2 node?

mongodb - 在查询中使用大写字母时,elasticsearch 将不起作用