Find a document, alter one of its sub-sub-documents, save it and... no changes saved.

38 views
Skip to first unread message

Hylke Bron

unread,
Apr 25, 2013, 8:44:53 AM4/25/13
to mongoo...@googlegroups.com
Hello,
 
I am building an application with MongoDB and Mongoose. Ive thought of a nice datastructure, which is similar as the following:
 
var childSchema = mongoose.Schema({
  name
: String,
  age
: Number,
  toy
: String
});

var adult = mongoose.Schema({
  name
: String,
  age
: Number,
  married
: Boolean,
  child
: {type: mongoose.Schema.Types.Mixed} // I use mixed so im able to put just 1 child of type childSchema in here,
                                             
//storing it in the initial employer schema
});

var employerSchema = mongoose.Schema({
  name
: String,
  company
: String,
  employee
: {type: mongoose.Schema.Types.Mixed} // I use mixed so ill be able to put in only 1 employee
});

 

When i made the corresponding models, and stored some employers, ill have a few documents, with in each document an employer, that has an employee, which has a child. (remember this is a fictive case).
 
Now, i want to change the name of an adult and the toy of its child. I assumed i could do the following:
 
employerModel.findOne({name: "employer_name"}, {lean: false}, function(err, employer){
 
// Check if the query worked out
 
if(err || employer == null) handleErr();
 
 
// We have an employer document now, change stuff for adult and child
  employer
.employee.name = "alteredname";
  employer
.employee.child.toy = "latestXBOX";

 
// Next step is to simply save this altered employer, and voilla, it should be solved, or so i thought
  employer
.save(function(error, saved_employer){
   
// Check if it worked
   
if(error || saved_employer == null) handleErr();
   
   
// It worked (at least in my case)
   
// All variables are nicely set as i wanted them, id think it is successfull... but ofcourse im not
    console
.log(JSON.stringify(saved_employer));
 
});
});

 

Well, if you followed the code a bit, i should have changed the document now, but poor me, it didnt work. Even though the save method was called correctly, and the saved_employer shows all altered values correctly, when i were to do a find on this element again, nothing is changed.
 
However, it does work when i would only alter attributes that are in the top level of employer (name, company etc), but once i go deeper inside the structure, everything fails.
 
My question is, why is this, is this a bug, and which ways can i create a work around for this issue.
 
Thanks in advance,
 
Hylke Bron
 
Reply all
Reply to author
Forward
0 new messages