【问题标题】:Adding field in Mongoose plugin gives "TypeError: Invalid value for schema path `CreatedBy.type`"在 Mongoose 插件中添加字段会给出“TypeError:模式路径 `CreatedBy.type` 的无效值”
【发布时间】:2014-12-18 03:33:08
【问题描述】:

我正在尝试制作 CreatedBy Mongoose 插件,但是当尝试使用 ObjectId 作为它给我的字段类型时("account" 已经是另一个定义的集合):

TypeError: Invalid value for schema path `CreatedBy.type`

&这里是插件代码:

mongoose =  require 'mongoose'
module.exports = exports = updatedByPlugin = (schema, options) ->
  schema.add CreatedBy:
    type: mongoose.Schema.Types.ObjectId
    ref: "account"
  schema.pre "save", (next) ->
    @CreatedBy = options.accountId
    next()
    return

  schema.path("CreatedBy").index options.index  if options and options.index
  return

那么我如何修改ref 值以使其工作?

【问题讨论】:

  • 你应该用适当的语言标签(coffeescript?)来标记它。
  • 但它与Coffeescript无关,如果代码是用JavaScript编写的,它也可以这样做
  • 那么关于C中指针的问题应该只标记指针,而不是C?如果它是用 C++ 编写的,那毕竟可能是同样的问题。目标是尽可能广泛地撒网。遵循咖啡脚本和猫鼬标签的人可能比遵循 JS 和猫鼬的人更容易为您提供帮助。语法的改变需要一些心理上的调整。您的解决方案甚至可能与咖啡脚本的编译方式有关,尽管您更有可能在此过程中更改了其他内容。 (我所有的 JS mongoose 模型都有 type 然后是 objectId。)
  • 询问具体的包不是语言本身的问题,但既然不会有坏处,我还是加了!

标签: node.js mongodb coffeescript mongoose mongoose-plugins


【解决方案1】:

好吧,你不会相信的,但我通过这种方式添加 CreatedBy 字段解决了它

schema.add CreatedBy:
   ref: "account"
   type: mongoose.Schema.Types.ObjectId

是的,只需将 2 行换成 reftype! .交换这两行代码会破坏代码,这很奇怪:| !!!

【讨论】:

  • 不过,在 2018 年,这就是解决方案。
猜你喜欢
  • 2019-09-12
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
相关资源
最近更新 更多