我想从basicData中给我的id作为我整个Company对象的ObjectID。这怎么可能?
我已经尝试过:_id: { type: mongoose.Types.ObjectId, ref: "Company" }
,但是不起作用...
你有解决办法吗?
我的代码:
import mongoose, { Schema, Document, Collection, mongo } from "mongoose";
const CompanySchema = new Schema(
{
basicData: {
_id: { type: mongoose.Types.ObjectId, auto: true }, // that id I want to give her the complete ObjectID of Company
tasks: {
type: [],
validate: {
validator: (arr: any) => {
return arr.length > 0;
},
message: "You must provide more than 0 tasks.",
},
title: { type: String, required: [true, "title is required"] },
},
partner: {
type: Number,
required: [true, "partner is required"],
min: 0,
max: 10,
},
riskFactor: {
type: Number,
required: [true, "riskFactor is required"],
min: 0,
max: 10,
},
name: { type: String, required: [true, "name is required"] },
},
},
{
versionKey: false,
typePojoToMixed: false,
}
);
const Company = mongoose.model("Company", CompanySchema);
export default Company;
答案 0 :(得分:0)
您可以在companySchema文件中创建一个basicSchema,插入时将自动获得_id
:
// Company.js
const BasicDataSchema = new Schema({
tasks: {
type: [],
validate: {
validator: (arr: any) => {
return arr.length > 0;
},
message: "You must provide more than 0 tasks.",
},
title: { type: String, required: [true, "title is required"] },
},
partner: {
type: Number,
required: [true, "partner is required"],
min: 0,
max: 10,
},
riskFactor: {
type: Number,
required: [true, "riskFactor is required"],
min: 0,
max: 10,
},
name: { type: String, required: [true, "name is required"] }
});
const CompanySchema = new Schema({
basicData: BasicDataSchema,
...
});