Friday, 5 May 2017

How to save data for Mongodb Nested schema using mongoose

I want to structure mongodb in such a way that it store data in following way.

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

What i have done so far for structure after little searching

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

Now what is the best way to save data using express/nodejs and mongoose ?



via Rakesh Soni

No comments:

Post a Comment