小编Mud*_*med的帖子

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

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

我用 postgresql 在 rails 中这样做:

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

## Candidate and Employer
  has_one :user, :as => :profileable
Run Code Online (Sandbox Code Playgroud)

对于 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
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

polymorphic-associations mongoose mongodb node.js

4
推荐指数
1
解决办法
2699
查看次数