2

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();
  });
  });
2
  • 1
    How are you inserting the documents in your Mongoose code, can you show that part as well? Commented Aug 30, 2016 at 15:16
  • @chridam I just updated the post. I was also thinking of making the sketches array a subdocument of the User document but I wasn't sure the best way to go about doing that exactly. Commented Aug 30, 2016 at 15:26

2 Answers 2

5

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}
    }
  ]
});
Sign up to request clarification or add additional context in comments.

1 Comment

That seems like it works, I ended up creating a sub document for sketches instead. I'll post another answer with what I did.
3

I ended up creating a sub document for sketches and making that a child of the User Schema:

var sketchSchema =  mongoose.Schema({ name: String, sketchData : Array
  });
var SavedSketch = mongoose.model('Sketch', sketchSchema);
// });


var userSchema =  new mongoose.Schema({
  username: {type: String, unique : true},
  password: {type: String},
  firstname: String,
  lastname: String,

  sketches:[sketchSchema]


var User = mongoose.model('User', userSchema);

module.exports = User;

2 Comments

What is the difference between declaration: password: {type: String} vs firstname: String ?.
@Sunny {type : String} is equal : String. The first pattern, we can add more option like password: {type: String, unique: true, requried: true }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.