1

I have this code:

balanceModel.findOne({year: parseInt(req.params.year)},function(err,data){

   data.months['weirdber'] = {
       x: 'y'
   };

    data.save(function(e,d){
        console.dir(e);
        res.json(d);
    });

});

null is printed when I call it, so definitely no error is thrown.

The callback's d argument holds the correct data, including the newly added property.

Yet, when I retrieve the collection later, there is no property 1999 in years.

I have mad absolutely sure that I do not retrieve the wrong collection later on.

This is my Schema, which I have cut down from a compley one with nested schemas to this, let's call it super simple to avoid bad words, stuff. Still not working.

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var BalanceSchema = new Schema({
    year: Number,
    months: Object
});

module.exports = mongoose.model('Balance', BalanceSchema);

What is going on here?

Stennie
  • 63,885
  • 14
  • 149
  • 175
user2422960
  • 1,476
  • 6
  • 16
  • 28
  • Hell, I meant to write `false`. Anyways, I have updated the question. There is no error. The above was just meant to be a simple explanation. The real code of course does not just log `!!e` – user2422960 Jan 21 '15 at 14:07
  • Done. I would be super-duper happy if you could recommend a schema for this problem. I'm tearing my hairs out. – user2422960 Jan 21 '15 at 14:45
  • Looks like a dupe of http://stackoverflow.com/questions/19165571/updating-a-subfield-in-a-mongodb-document-using-findone-and-save. But it would be better to make `months` an array to keep data out of your object keys. – JohnnyHK Jan 21 '15 at 14:51
  • I first declared it as an array. However, I found it would be convenient if I could retrieve a desired month via its name, since this is what is passed to the REST API. – user2422960 Jan 21 '15 at 14:53
  • 1
    You can still do that with an array by using the `$` or `$elemMatch` projection operators when querying. See http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection/12241930#12241930 – JohnnyHK Jan 21 '15 at 14:56
  • i think you need to mark it as changed. though this is 1 yr old questions i will still give my opinion :) try adding `data.markModified('month'); `before you save :) – Rei Dien Jan 09 '16 at 07:03

0 Answers0