【问题标题】:Add document to an embedded document array将文档添加到嵌入式文档数组
【发布时间】:2012-04-12 23:21:21
【问题描述】:

我正在尝试将嵌入文档添加到现有文档字段。我通过搜索找到了one fitting answer,但我遇到了错误。我正在使用 node.js、Express 和 Mongoose。

我的数据库架构:

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

var compo = new Schema({
    name        : String,
    description : String,
    entries     : [entry]
});

我正在尝试使用以下代码更新条目数组

var entry = new entryModel();
entry.name = "new name";
entry.description= "new description";

compoModel.findOne(query, function (err, item) {
  if (item) {
    item.entries.push(entry);
    item.save(function (err) {
      if (!err) {
        log.debug('Entry added successfully.');
      } else {
        log.error("Mongoose couldn't save entry: " + err);
      }
    });
  }
});

它产生一个错误:TypeError: Object.keys called on non-object

我错过了什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    通过清除子文档数组解决了我的类似问题(相同的错误)。它是在定义子文档方案之前填充的。 至少我认为是这样的。

    例如:

    var token = new Schema( { value: String, expires: Date } )
    var user = new Schema( { username: String, tokens: [token] } )
    

    .. 并且,在定义“令牌”方案之前,我有以下条目:

    { username: 'foo', tokens: ['123456'] }
    

    .. 所以,清除令牌为我做了。

    user.tokens = []
    user.save()
    

    【讨论】:

      【解决方案2】:

      所以我设法通过Model.update 方法让它工作,只需将一个新对象添加到compo.entries 列表并调用compoModel.update

      【讨论】:

        猜你喜欢
        • 2016-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多