Как установить пользовательскую модель коллекции в качестве типа данных в mongo?

#mongodb #mongoose #mongoose-schema

#mongodb #мангуст #mongoose-schema

Вопрос:

Итак, я создал model Client с помощью ClientShema, и теперь я создаю model Company. Одно из полей должно быть типа Client, я пытался это сделать, но, похоже, происходит сбой

вот некоторый код:

 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:

Добро пожаловать в 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);
  

Надеюсь, это решит вашу проблему.