Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble saving in Mongoose 3

I'm trying to update some content in Mongoose.js 3.1.2 and I can't get these two functions to work. Any ideas why? Thanks...

function(req, res) {
  Content.findById(req.body.content_id, function(err, content) {
    // add snippet to content.snippets
    content.snippets[req.body.snippet_name] = req.body.snippet_value;
      content.save(function(err) {
        res.json(err || content.snippets);
    });
  }
}


function(req, res) {
  Content.findById(req.body.content_id, function(err, content) {

      // delete snippets
      delete content.snippets[req.body.snippet_name];
      //content.snippets[req.body.snippet_name] = undefined; <-- doesn't work either

      content.save(function(err) {
        res.json(err || "SUCCESS");
      });

  });
}

My schema looks something like this:

contentSchema = new Schema(
  title: String,
  slug: String,
  body: String,
  snippets: Object
);
like image 795
Pardoner Avatar asked Oct 06 '12 05:10

Pardoner


1 Answers

You may need to mark the paths as modified. Mongoose may not check the object properties since you didn't create an embedded schema for them.

function(req, res) {
  Content.findById(req.body.content_id, function(err, content) {
    // add snippet to content.snippets
    content.snippets[req.body.snippet_name] = req.body.snippet_value;
    content.markModified('snippets');  // make sure that Mongoose saves the field
      content.save(function(err) {
        res.json(err || content.snippets);
    });
  }
}
like image 57
Bill Avatar answered Oct 01 '22 11:10

Bill