【问题标题】:default value for ref collection in mongoose猫鼬中 ref 集合的默认值
【发布时间】:2018-12-03 03:09:50
【问题描述】:

我有一个用户个人资料,我有一个“收入”字段,它在架构中看起来像这样

收入:{ 类型:Schema.Types.ObjectId, 参考:“收入” }

创建新用户时如何为收入字段设置默认值?我不能这样做

earning: {
    type: Schema.Types.ObjectId,
    ref: 'Earning',
    default: 0
  }

我得到了错误 路径“earning”处值“0”的值“0”转换为 ObjectId 失败

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您在这里做错的是尝试在 ID 字段上投射数字。由于它是另一个对象 Id 字段的引用,因此您不能将其设置为 0。您需要做的是在db中创建用户时设置null,并将其初始化为null值。 喜欢:

    earning: {
      type: Schema.Types.ObjectId,
      ref: 'Earning',
      default: null
    }
    

    【讨论】:

    • 我猜 you can set 0 to it 应该是 you can not set 0 to it
    • @SergioM。不,你不能,我得到了我测试过的错误。
    • 但我必须在我的 api 中做一些修改?就像收入 = 收入 === null 一样? 0:未定义?
    • 能否详细说明一下?
    【解决方案2】:

    据我了解,earning 表示用户赚了多少,所以它应该是Number 类型而不是ObjectId

    所以尝试将您的架构更改为

    earning: {
    type: Number,
    ref: 'Earning',
    default: 0
    

    }

    所以你可以使用0

    注意:如果您出于某种原因应该使用ObjectId,那么“Haroon Khan”的答案就是正确答案。

    【讨论】:

      【解决方案3】:

      当基于具有“ObjectId”类型键和另一个集合的引用的模式实例化文档时,我发现设置“默认”值的唯一方法是使用 Mongoose 中间件here 描述的架构级别。例如,当作者未登录时,将评论的作者设置为用户集合中的默认“访客”文档可能如下所示:

      // user document in MongoDB
      {  
        _id: ObjectId('9182470ab9va89'),
        name: 'guest'
      }
      
      // CommentSchema
      const mongoose = require('mongoose')
      
      const CommentSchema = mongoose.Schema({
        author: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
        body: String
      })
      
      CommentSchema.pre('save', function (next) {
        this.author == null ? this.author = '9182470ab9va89' : null
        next()
      })
      
      module.exports = mongoose.model('Comment', CommentSchema)
      

      本示例使用 'save' 预挂钩和在架构中硬编码的 ObjectId 用于演示目的,但您可以将 ObjectId 的硬编码替换为对后端的调用,或者您希望在其中获取该值在那里。

      【讨论】:

        猜你喜欢
        • 2020-09-27
        • 1970-01-01
        • 2018-07-05
        • 2016-06-20
        • 2020-06-13
        • 2021-01-18
        • 1970-01-01
        • 2015-09-25
        • 2018-10-02
        相关资源
        最近更新 更多