在Mongoose中节省麻烦3

Par*_*ner 5 mongoose mongodb node.js

我正在尝试更新Mongoose.js 3.1.2中的一些内容,我无法使这两个功能起作用.有什么想法吗?谢谢...

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");
      });

  });
}
Run Code Online (Sandbox Code Playgroud)

我的架构看起来像这样:

contentSchema = new Schema(
  title: String,
  slug: String,
  body: String,
  snippets: Object
);
Run Code Online (Sandbox Code Playgroud)

Bil*_*ill 10

您可能需要将路径标记为已修改.Mongoose可能无法检查对象属性,因为您没有为它们创建嵌入式架构.

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);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)