[英]How to save data in the form of Mongodb Nested schema using mongoose
我想以以下方式存儲mongodb的方式來構造數據。
{ "question" : "Was today's decision right?", "choices" : [ { "text" : "yes", "votes" : [ { "ip" : "123.123.123.123", "time" : "123444" } ] }, { "text" : "no", "votes" : [ { "ip" : "123.123.123.123", "time" : "123444" }, { "ip" : "123.123.123.123", "time" : "123444" }, { "ip" : "123.123.123.123", "time" : "123444" } ] } ] }, { "question" : "Was yesterday's decision right?", "choices" : [ { "text" : "yes", "votes" : [ { "ip" : "123.123.123.123", "time" : "123444" } ] }, { "text" : "no", "votes" : [ { "ip" : "123.123.123.123", "time" : "123444" }, { "ip" : "123.123.123.123", "time" : "123444" }, { "ip" : "123.123.123.123", "time" : "123444" } ] } ] }
經過很少的搜索,到目前為止,我對結構所做的工作
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var voteSchema = new Schema({ ip: String }); var choiceSchema = new Schema({ text: String, votes: [voteSchema] }); var PollSchema = new Schema({ question: { type: String, required: true }, choices: [choiceSchema] }); module.exports = mongoose.model('Polls', PollSchema);
現在,如果我使用以下代碼保存硬編碼數據,則可以正常工作
var poll = new Poll({ question : reqBody.question, choices : [ { text : "yes", votes : [ { ip : "123.123.123.123" } ] }, { text : "no", votes : [ { ip : "123.123.123.123", }, { ip : "123.123.123.123", }, { ip : "123.123.123.123", } ] } ] }); poll.save(function(err, data) { res.json(data); });
但是我不知道如何從前端(html / js)發送數據?
得到的解決方案:
首先將以下代碼放入控制器文件中
var reqBody = req.body; var choices = reqBody.choices; var choicesnew = []; for (var i = choices.length - 1; i >= 0; i--) { var votes = []; var choice = {text:choices[i],votes: votes}; choicesnew.push(choice); } var newPoll = { question: reqBody.question, choices: choicesnew } var poll = new Poll(newPoll); poll.save(function(err, data){ res.json(reqBody); });
現在使用前端傳遞數據
<form action="#"> <input type="text" name="question" placeholder="question"> <input type="text" name="choices" placeholder="choices"> <input type="text" name="choices" placeholder="choices"> <input type="text" name="choices" placeholder="choices"> <input type="text" name="ip" placeholder="ip"> <input type="submit"> </form>
盡管某些數據應由nodejs處理。 我只是為了簡單起見在這里列出。
現在我正在使用ajax將數據從前端發送到節點
$("form").on('submit', function(event) { event.preventDefault(); $.ajax({ url: '/new', type: 'POST', data: $(this).serializeArray(), }) .done(function(data) { console.log(data); }) .fail(function() { console.log("error"); }) .always(function() { console.log("complete"); }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.