Py学习  »  MongoDB

如何在MongoDB中关联两个集合

Thamaraiselvam • 4 年前 • 764 次点击  

我已经创建了两个集合 供应商和员工 供应商集合具有员工的引用“ 雇员ID:[字符串] 我也应该这么做吗?那是个好主意吗?在两个集合中添加引用?

如果我想让所有员工都写上他们的公司名称呢?我很困惑。

雇员

const employeeSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  address: String,
  email: String,
  designation: String,
  contact_number: Number,
  contract_start: Date,
  contract_end: Date
});

小贩

const vendorSchema = Schema({
    _id: Schema.Types.ObjectId,
    name: String,
    address: String,
    email: [String],
    contact_number: [Number],
    contract_start: Date,
    contract_end: Date,
    emplyoee_id:[String]
});
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40664
 
764 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Ashwanth Madhav
Reply   •   1 楼
Ashwanth Madhav    5 年前

对于环回框架

我已经用环回框架完成了。例如,用户集合和项目集合对每个用户都有,可以有多个项目,每个项目只有一个用户。

在项目模型中

"relations": {
   "user": {
   "type": "belongsTo",
   "model": "user",
   "foreignKey": "id"
}}

在用户模型中

"relations": {
  "projects": {
  "type": "hasMany",
  "model": "project",
  "foreignKey": "project_user_id"
}}
robertsLando
Reply   •   2 楼
robertsLando    5 年前

在Mongoose模型中,可以使用对另一个模型的引用来定义属性。检查猫鼬 popolate

例子:


const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);