loremIpsum1771 loremIpsum1771 - 3 months ago 17
JSON Question

How to create nested object in MongoDB schema

I currently have the following schema for a MongoDB document which is supposed to save user data:

var userSchema = new mongoose.Schema({
username: {type: String, unique : true},
password: {type: String},
firstname: String,
lastname: String,
sketches:
[
{name: String,
sketch: Array}
]


The sketches attribute needs to be an array objects where each object associates the name of a sketch and an array which holds the sketch data. For some reason, the schema ends up being created as the following:

{
"__v" : 1,
"_id" : ObjectId("57c4d7693aa85cea2acf4d4d"),
"firstname" : "test",
"lastname" : "name",
"password" : "password123",
"sketches" : [
{
"sketch" : []
}
],
"username" : "testname"
}


I'm not exactly sure the correct format for creating nested objects in MongoDB but I was assuming that it would be the same as it would for JSON. How should the schema be structured to yield an array of objects.

EDIT:



web service to insert into document from PUT request:

app.route("/addSketch/:username").put(function(req, res, next) {
var user_name = req.params.username;
User.findOne({username:user_name},function(err,foundObject){
if(err){
console.log("error");
res.status(500).send();
}
else{
if(!foundObject){
res.status(404).send();
}
else{

if(req.body.strokes && req.body.sketchName){
var sketchObj = [];
sketchObj[req.body.sketchName] = req.body.strokes;
foundObject.sketches.push(req.body.sketchData);
}
foundObject.save(function(err,updatedObject){
if(err){
console.log(err);
res.status(500).send();
}
else{
res.send(updatedObject);
}
});
}
}

});


console.log('saving on server');
var form = formidable.IncomingForm();

console.log(form);
console.log('the type of the request received is', (typeof req));

form.parse(req, function(err, fields, files) {
res.writeHead(200, {"content-type": "text/plain"});
res.write('received upload:\n\n');
var name = fields.name;
var newSketch = new SavedSketch();
newSketch.name = name;
newSketch.sketchData = fields.value;
newSketch.save(function(err,savedObject){
if(err){
console.log(err);
res.status(500).json({status:'failure'})
}
else{
console.log("ID: " + fields.value.id + " strokeData:" + fields.value.strokes);
res.json({status: 'success'});
}
});

res.end();
});
});

Answer

Schema

var userSchema =  new mongoose.Schema({
  username: {type: String, unique : true},
  password: {type: String},
  firstname:{type: String},
  lastname: {type: String},
  sketches: [{
            name: String,
            sketch : {type : Array}
        }]
Comments