【问题标题】:How to put embedded document from one document into another document using Mongoose?如何使用 Mongoose 将嵌入文档从一个文档放入另一个文档?
【发布时间】:2011-09-01 18:51:21
【问题描述】:

我想要做的应该是直截了当的,但由于某种原因,我很难弄清楚这一点。我有以下 Mongoose 模式(简化)。

var Status = new Schema({
    name : { type: String, required: true },
    description : { type: String }
});

var Category = new Schema({
    statuses : [Status], // contains a list of all available statuses
    // some other attributes
});

var Book = new Schema({
    statuses : [Status], // preferably this would not be an array but a single document, but Mongoose doesn't seem to support that
    // some other attributes
});

现在,我想做以下事情:

  1. 检索类别文档
  2. 查找特定的嵌入式状态文档(基于请求参数)
  3. 将特定的嵌入状态文档分配给特定的书籍文档。我想替换现有的图书状态,因为在任何给定时间都应该为一本书设置一个状态。

这是我目前正在做的事情:

mongoose.model('Category').findOne({_id: id}, function(err, category){
    if(err) next(err);
    var status = category.statuses.id(statusId); // statusId available via closure
    book.statuses[0] = status; // book available via closure; trying to replace the existing status here.
    book.save(function(err){
        if(err) next(err);
        next();
    });
});

以上似乎运行良好,我没有收到任何错误。但是,新状态不会保存到文档中。下次我输出更​​新后的 Book 文档时,它仍然是旧状态。我对此进行了调试, find() 方法以及设置状态似乎都很好。

我现在唯一能想到的是,不知何故,我分配的状态值不是用 Mongoose 保存的正确格式。虽然,我希望那时会出现某种错误消息。

或者也许有更好的方法来做这一切?

【问题讨论】:

    标签: mongodb mongoose express


    【解决方案1】:

    这可能是因为您正在尝试复制一个嵌入的文档,该文档本身可能有一个与之关联的 ObjectId。尝试在Book 中保存重复的Status 将创建两个具有相同ObjectId 的嵌入文档。尝试创建一个新的 Status 对象并复制字段。

    ObjectsIds 上很难找到嵌入文档的文档,但在这里提到了它们:http://mongoosejs.com/docs/embedded-documents.html

    【讨论】:

      猜你喜欢
      • 2012-06-08
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多