node.js - Mongoose 架构类型字符串不起作用

标签 node.js mongodb mongoose

我正在更新我的数据库,但我无法理解下面的架构发生了什么:

{ 
  ref             : String,
  event           : {
    name          : String,
    data          : mongoose.Schema.Types.Mixed,
    type          : mongoose.Schema.Types.Mixed, // Declaring this as String makes parent(event) undefined. 
  }
}

event.type 的输入数据是字符串,但是当我这样声明它时,所有现有文档和新文档的 event 字段都变为 undefined

即在主函数(如下)中,我得到Cannot set property 'type' of undefined

// Main function
model
  .find({ 'event.type' : { $exists: false }})
  .exec(function(err, data) {
    if (err) return console.log(err);

    for (var i = 0, len = data.length; i<len; i++) {
      data[i].event.type = data[i].ref; // <-- Error Occurs here: Cannot set property 'type' of undefined
      data[i].save()
    }
  })

很想获得一些见解。如有任何帮助,我们将不胜感激!

最佳答案

属性type在Mongoose中具有特殊含义。

如果您想将其用作架构中的属性名称,您需要告诉 Mongoose 不要将其视为特殊的:

var schema = new Schema({ 
  ref   : String,
  event : {
    name : String,
    data : mongoose.Schema.Types.Mixed,
    type : String,
  }
}, { typeKey : '$type' });

更多信息here ;

关于node.js - Mongoose 架构类型字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645299/

相关文章:

node.js - 当 docker 容器崩溃时数据会发生什么

javascript - 如何仅将错误消息从模型传递到 Controller (Mongoose)?

javascript - 修复错误: Cannot read property 'path' of undefined

node.js - 通过 id 查找 mongoose 数组中的对象

javascript - 无法使用 Mongoose 模型

node.js - 使用 Node js 进行多个连接时 Mongodb 崩溃

Node.js 在 app.post 之外获取响应

使用 Golang mongo-driver 的 MongoDB 自动增量 ID

mongoose - 将 Bluebird 用于 Mongoose promise 的正确方法是什么?

javascript - NodeJS 处理发布文件并返回文件