Mongoose - 如何找到已经在使用的鉴别器 [英] Mongoose - how to find discriminators already in use

查看:51
本文介绍了Mongoose - 如何找到已经在使用的鉴别器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 REST API 中使用 MongoDB 和 Mongoose.某些部署需要副本集,因此需要单独的读/写数据库,因此我在 API 中有单独的读/写连接.但是,更简单的部署不需要副本集,在这些情况下,我将读/写连接指向同一个 MongoDB 实例和数据库.

I'm using MongoDB and Mongoose in a REST API. Some deployments require a replica set, thus separate read/write databases, so as a result I have separate read/write connections in the API. However, more simple deployments don't need a replica-set, and in those cases I point my read/write connections to the same MongoDB instance and database.

我的一般方法是在 API 启动时为两个连接创建所有模型.即使读/写连接连接到同一个数据库,我也能够在两个连接上创建相同的模型而不会出错.

My general approach is to create all models for both connections at API start up. Even when read/write conns are connecting to same database, I am able to create the same models on both connections without error.

let ReadUser = dbRead.model('User', userSchema);
let WriteUser = dbWrite.model('User', userSchema);
// no error even when dbRead and dbWrite point to same DB

直到我开始使用 Mongoose 鉴别器时才会出现问题.

Trouble comes when until I start using Mongoose Discriminators.

let ReadSpecialUser = ReadUser.discriminator('SpecialUser', specialUserSchema);
let WriteSpecialUser = WriteUser.discriminator('SpecialUser', specialUserSchema);

// Results in this Error when read and write point to same DB:
// Error: Discriminator with name "SpecialUser" already exists 

我正在寻找一种优雅的方式来处理这个问题.有没有办法在数据库中查询已经在使用的鉴别器?

I'm look for an elegant way to deal with this. Is there a way to query the db for discriminators that are already in use?

推荐答案

根据 Mongoose API 文档 这样做的方法是使用 Model.discriminators.所以在上面的例子中它会是

According to the Mongoose API docs the way to do this is to use Model.discriminators. So in the case above it would be

ReadUser.discriminators 

WriteUser.discriminators 

然而,这不会为我带来任何回报.什么工作是使用

However this doesn't return anything for me. What does work is using

Object.keys(Model.discriminators)

正如预期的那样,这会为您提供您之前设置的鉴别器名称的字符串数组.

As expected this gets you an array of strings of the discriminator names you've set previously.

如果您想使用现有的判别器模型并知道其名称,您可以使用 Model.discriminators.discriminatorName.在您的示例中,它将是:

If you want to use the existing discriminator model and know its name what you can do is use Model.discriminators.discriminatorName. In your example it would be:

let ReadSpecialUserDocument = new ReadUser.discriminators.SpecialUser({
  key: value,
  key: value,
});

ReadSpecialUserDocument.save()

当您需要在不同时间重复使用鉴别器,并且它的名称以某种方式与您的数据相关联时,这会很有用.

This can be useful when you need to reuse the discriminator at different times, and its name is tied to your data in some way.

这篇关于Mongoose - 如何找到已经在使用的鉴别器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆