定义与现有旧式MongoDB模式的模式的猫鼬关系

时间:2019-04-09 03:28:01

标签: node.js mongodb mongoose

我正在用NodeJ重写生产Ruby应用程序;我们的Ruby模式定义了MongoDB对象,如下例所示。

一个公司有许多用户,一个用户属于许多公司

// User
{
  "_id" : ObjectId("5b3a8344f7e49c50b882a4a3"),
  "name" : "Example User",
  "company_ids" : [ 
    ObjectId("5b3a8344f7e49c50b882a47e"), 
    ObjectId("5b3a8344f7e49c50b882a47f"), 
    ObjectId("5bdb97bff7e49c1e0a5964f3")
  ],
  "updated_at" : ISODate("2019-04-05T23:07:27.001Z"),
  "created_at" : ISODate("2018-07-02T19:55:49.422Z")
}

// Company
{
  "_id" : ObjectId("5b3a8344f7e49c50b882a47e"),
  "name" : "Example Company",
  "number" : 1, 
  "updated_at" : ISODate("2019-04-05T23:07:27.001Z"),
  "created_at" : ISODate("2018-07-02T19:55:49.422Z")
}

到目前为止,我一直在尝试通过以下方式定义模型之间的关系,但是我没有成功,我认为猫鼬正在尝试寻找companyIds,但在数据库,但我不知道如何手动指定要映射的字段。

// ./src/models/User.js
const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
  name: String,
  companies: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Company', 
    companyIds: 'company_ids' // <- not working
  }]
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
})
mongoose.model('User', UserSchema)

-

// ./src/models/Company.js
const mongoose = require('mongoose')

const CompanySchema = new mongoose.Schema({
  name: String,
  number: Number
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
})

mongoose.model('Company', CompanySchema)

1 个答案:

答案 0 :(得分:0)

看看Mongoose docs,最好的选择是aliases,您可以这样编写模式:

const mongoose = require('mongoose')

var companySchema = new mongoose.Schema({
  "name": String,
});
var Company = mongoose.model('Company', companySchema);

var compA = Company({ name: 'a'});
var compB = Company({ name: 'b'});
var compC = Company({ name: 'c'});

var userSchema = new mongoose.Schema({
  "company_ids": {
    type: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Company',
    }], 
    alias: 'companies'
  }
})
var User = mongoose.model('User', userSchema);
var user = new User({ companies: [compA, compB, compC]});
console.log(user)
console.log(user.companies);

记录对象时,您获得{ company_ids: [compA, compB, compC]},但除此之外,您可以使用“ companies”字段,如下所示:

var user = new User({ companies: [compA, compB, compC]});
console.log(user) // { company_ids: [compA, compB, compC] }
console.log(user.companies); // [compA, compB, compC]
user.companies = [compA, compB]
console.log(user.companies); // [compA, compB]