具有mongoose和node.js的多态用户模型

时间:2014-07-03 18:45:56

标签: node.js mongodb mongoose polymorphic-associations

我正在使用mean.js样板制作应用程序。它是一个招聘引擎,用户作为雇主和候选人。现在,雇主和候选人应该作为单独的文件存储,每个用户必须只有一个雇主或候选人,因为每个候选人或雇主都需要使用用户对象登录。

我使用postgresql在rails中执行此操作:

## User
  belongs_to :profileable, :polymorphic => true

## Candidate and Employer
  has_one :user, :as => :profileable

使用mongoose这是我到目前为止使用的软件包' mongoose-schema-extend':

var extend = require('mongoose-schema-extend');

var UserSchema = new Schema({
    email: {
        type: String
    },
    password: {
        type: String
    }
}, { collection: 'users', discriminatorKey : '_type' });


var CandidateSchema = UserSchema.extend({
    Experience: {
        type: Number
    }
});

var EmployerSchema = user.user.extend({
    companyName: {
        type: String
    }
});

上面的代码有效,但在mongodb中只为_type属性设置为候选人或雇主的用户创建文档。

我认为它应该做的是将候选人,雇主和用户存储为单独的文件。我必须将雇主与公司和工作联系起来。此外,我需要分别用不同的标准查询候选人和雇主。

实现该功能的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

可以使用mognoose鉴别器处理scenairo。

根据mongoose docs:

  

判别器是一种架构继承机制。它们使您能够在相同的基础MongoDB集合之上拥有多个具有重叠模式的模型。

我找不到很多关于鉴别器的教程,但是,这是一个我发现有用的链接: http://thecodebarbarian.com/2015/07/24/guide-to-mongoose-discriminators

由于