猫鼬ref收集的默认值

时间:2018-06-24 08:41:47

标签: node.js mongodb mongoose

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

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

创建新用户时,该如何为收入字段设置默认值?我做不到

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

我遇到了错误 在路径“收入”处将值“ 0”强制转换为ObjectId

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

据我了解,prepareForSegue表示用户收入多少,因此应为override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddMemberVCSegue" { guard let destination = segue.destination as? AddMemberViewController else { return } destination.club = club } if segue.identifier == "TransactionVCSegue" { guard let Destination = segue.destination as? TransactionViewController, let selectedRow = self.tableViewMember.indexPathForSelectedRow?.row else { return } Destination.member = members[selectedRow] } } 类型,而不是earning

因此请尝试将模式更改为

Number

}

因此您可以使用ObjectId

注意:如果出于某种原因您应该使用earning: { type: Number, ref: 'Earning', default: 0 ,那么“ Haroon Khan”的答案就是正确的答案。

答案 2 :(得分:1)

当基于具有“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 的硬编码,或者您希望在其他情况下获取该值

相关问题