简体   繁体   English

如何在猫鼬模式中设置与已定义类型不同的属性类型?

[英]How do I set a different type of property in mongoose schema from the defined type?

I have a Mongoose schema set up for a user profile on a forum. 我在论坛上为用户个人资料设置了Mongoose模式。 What I'd like to do is set up the user's forum title to be an ObjectID and reference the Title schema. 我想做的是将用户的论坛标题设置为ObjectID并引用Title模式。 I already have this part set up. 我已经设置了这部分。 However by default I'd like for this field to be a string called "Noob" until a title is set from the user's profile which then would change this value to an ObjectID referencing the Title from the database. 但是,默认情况下,我希望此字段是一个名为“ Noob”的字符串,直到从用户的配置文件中设置了标题为止,然后该值会将其更改为引用数据库中标题的ObjectID

title: {
  type: mongoose.Schema.Types.ObjectId,
  ref: 'Title',
  default: 'Noob'
},

This is what I have and is basically what I'm wanting to achieve, however this throws an error because the default I set is a string and not an ObjectID . 这就是我所拥有的,并且基本上是我想要实现的,但是这会引发错误,因为我设置的默认值是字符串而不是ObjectID I'm not sure how to achieve this or what alternatives I may have. 我不确定如何实现这一目标或我可能有什么选择。

Since you've pointed out that you want to maintain the strong type ObjectId for performance reasons, you'll have to use that same type as the default. 由于您已经指出出于性能原因要保留强类型ObjectId ,因此必须使用与默认类型相同的类型。 You could use an id of all 0s for example: 例如,您可以使用全0的ID:

title: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Title",
    default: 00000000-0000-0000-0000-000000000000
}

You can then check for this and display "Noob" in its place later? 然后,您可以检查此内容并在以后显示“ Noob”吗?

You can just make it a string: 您可以将其设置为字符串:

title: {
  type: String,
  ref: 'Title',
  default: 'Noob'
},

You can still set it as an ObjectID -looking string later. 以后您仍然可以将其设置为看起来像ObjectID字符串。

You can't have it both ways: if you want a field to be an ObjectID type, then it needs to hold ObjectID s. 您不能同时使用这两种方法:如果您想让字段成为ObjectID类型,则它需要保留ObjectID If you want to be able to hold strings in it, then it needs to be of type String . 如果您希望能够在其中保存字符串,则它必须为String类型。

If title is a reference to an ObjectID in another collection, Mongoose will still cast an ObjectID -ish string to an ObjectID when it performs the lookup: 如果title是另一个集合中对ObjectID的引用,则Mongoose在执行查找时仍会将ObjectID -ish字符串转换为ObjectID

Title.find({ _id: doc.title }) will still lookup an ObjectID if the doc.title is a string. 如果doc.title是字符串,那么Title.find({ _id: doc.title })仍将查找ObjectID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM