Кажется, что разделение этого на разные схемы может быть хорошей идеей. Особенно, если другие люди будут принадлежать к той же компании.
Например, возможно, вы могли бы попробовать это:
const CompanySchema = new mongoose.Schema({
name: String,
// ... other company specific attributes
});
const Company = mongoose.model("Company", CompanySchema);
const UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
companies: [
{
company: { type: mongoose.Schema.Types.ObjectId, ref: 'Company' },
post: String,
timeInPost: String,
}
]
});
const User = mongoose.model("User", UserSchema);
И взаимодействие с моделями может выглядеть так:
(async () => {
try {
const company1 = await Company.create({ name: "Company 1" });
const company2 = await Company.create({ name: "Company 2" });
const user1 = await User.create({
firstName: "first",
lastName: "last",
companies: [
{
company: company1._id,
post: "....",
timeInPost: "....",
},
{
company: company2._id,
post: "....",
timeInPost: "....",
},
],
});
const users = await User.find({}).populate("companies.company"); // in order to populate the company with the document from the company collection
// users with companies info
} catch (error) {
console.log(error);
}
})();
Ссылка из документации goose: https://alexanderzeitler.com/articles/mongoose-referencing-schema-in-properties-and-arrays/