In my codebase, I have the following models:
CoupleModel.ts
import mongoose, { Model, Schema } from 'mongoose';
import { CoupleType } from '../types/coupleTypes';
const coupleSchema = new Schema(
{
user1: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
user2: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
},
{
timestamps: true,
}
);
export default coupleSchema;
const Couple: Model<CoupleType> = mongoose.model<CoupleType>('Couple', coupleSchema);
UserModel.ts
import mongoose, { Model, Schema } from 'mongoose';
import { UserType } from '../types/userTypes';
const userSchema = new Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
match: [/^\S+@\S+\.\S+$/, 'Please use a valid email address.'],
},
},
{
timestamps: true,
}
);
const User: Model<UserType> = mongoose.model<UserType>('User', userSchema);
export default User;
Additionally, I have defined these types:
userType.ts
import { Document } from 'mongoose';
export type UserType = Document & {
name: string;
email: string;
};
coupleType.ts
import { Document, Types } from 'mongoose'; import { UserType } from './userTypes';
export type CoupleType = Document & {
user1: Types.ObjectId | UserType;
user2: Types.ObjectId | UserType;
};
To handle different operations, I declared user1
and user2
with the type Types.ObjectId | UserType
:
- If it's
couple.find()
, they will be of typeTypes.ObjectId
- If it's
, they will be of typecouple.find().populate(['user1','user2'])
UserType
- In the
couple.create({user1,user2})
, they will be of typeTypes.ObjectId
However, I encountered an issue:
const couples = await Couple.find().populate('user1').populate('user2');
const emailPromises = couples.map(async (couple) => {
const { user1, user2 } = couple;
console.log("🚀 ~ emailPromises ~ user1.email:", user1.email)
console.log("🚀 ~ emailPromises ~ user2.email:", user2.email)
});
Due to TypeScript not automatically inferring the type of user1
and user2
as UserType
, this error occurs:
Property 'email' does not exist on type 'ObjectId | UserType'.
Property 'email' does not exist on type 'ObjectId'.ts(2339)
How can I resolve this issue?