【发布时间】:2019-04-09 14:35:57
【问题描述】:
我正在用 NodeJs 重写一个生产 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")
}
到目前为止,我一直在尝试通过以下方式定义模型之间的关系,但我没有成功,我认为 mongoose 正在尝试查找 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)
【问题讨论】: