【问题标题】:trouble saving in Mongoose 3在 Mongoose 3 中节省麻烦
【发布时间】:2012-10-06 05:05:13
【问题描述】:

我正在尝试更新 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");
      });

  });
}

我的架构如下所示:

contentSchema = new Schema(
  title: String,
  slug: String,
  body: String,
  snippets: Object
);

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可能需要将路径标记为已修改。 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);
        });
      }
    }
    

    【讨论】:

    • 是的!我怎么错过了。谢谢比尔
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 2023-02-06
    • 2010-11-20
    • 2017-05-03
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    相关资源
    最近更新 更多