如何在mongo中将自定义收集模型设置为dataType?

时间:2019-04-21 21:39:57

标签: mongodb mongoose mongoose-schema

因此,我已经使用ClientShema创建了模型Client,现在正在创建模型Company。其中一个字段应为“客户端”类型,我尝试这样做,但似乎崩溃了

下面是一些代码:

const userSchema = new mongoose.Schema({
email: {
    type: String,
},
username: {
    type: String,
    required: false
},
createdAt: {
    type: Date,
    required: true
},
_id: {
    type: String,
    required: false,
}
}, { collection: 'User' });

const User = mongoose.model('User', userSchema);

这是我的文件,我想在其中使用先前提供的模型。

const client = require('./client');
const companySchema = new mongoose.Schema({
   _id: {
       type: String,
       required: true
   },
   logo: {
       type: String,
       required: false
   },
   companyName: {
       type: String
   },
   clients: {
       type: [client.Client]
   }
},  { collection: 'Company' });

const Company = mongoose.model('Company', companySchema);

1 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow

const client = require('./client');// need to include the schema file
var ClientSchema = mongoose.model('Client').schema;// 'Client' is name of Schema
const companySchema = new mongoose.Schema({
   _id: {
       type: String,
       required: true
   },
   logo: {
       type: String,
       required: false
   },
   companyName: {
       type: String
   },
   clients: {
       type: [ClientSchema]
   }
},  { collection: 'Company' });

 const Company = mongoose.model('Company', companySchema);

希望这可以解决您的问题。