I am using mongoose with Nextjs. If you look at the Review Schema below. It is linked with User schema and I am using the Review schema with populate in my React page to get the User document data, i-e; fullName.
Is there a way i can get types around the User document when populated inside Review?
I’ve tried (review?.user as User)?.fullName) which I’ve attached as well.
import { Document, InferSchemaType, Schema, model, models } from 'mongoose';
export const ReviewSchema = new Schema(
{
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
business: { type: Schema.Types.ObjectId, ref: 'Business', required: true },
rating: { type: Number, required: true, min: 1, max: 5 },
comment: { type: String, required: false },
images: { type: [String], required: false },
},
{
timestamps: true,
},
);
export type Review = InferSchemaType<typeof ReviewSchema> & Document;
export const ReviewModel = models.Review || model('Review', ReviewSchema);
import { Document, InferSchemaType, Schema, model, models } from 'mongoose';
const UserSchema = new Schema({
email: {
type: String,
unique: [true, 'Email already exists!'],
required: [true, 'Email is required!'],
},
fullName: {
type: String,
required: [true, 'Fullname is required!'],
},
role: {
type: String,
enum: ['user', 'admin', 'owner'],
default: 'user',
},
password: { type: String },
image: { type: String },
businesses: [{ type: Schema.Types.ObjectId, ref: 'Business' }],
});
export type User = InferSchemaType<typeof UserSchema> & Document;
export const UserModel = models.User || model('User', UserSchema);
2
Answers
change this field ->
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true }
, and add new fielduser: { type: mongoose.Schema.Types.Mixed}
and when you populate user for reviews, set{as: "user"}
and then you can access user as entity.it is not best solution for your case…
You should try defining
User
andReview
asinterfaces
instead of usingInferSchemaType
as suggested in the docs. It might look like:Then when you
populate
: