I have a Mongo collection of Users and a collection of Addresses. Each address is owned by one user.Here are my schema classes:
export type UserDocument = User & mongoose.Document
@Schema({ timestamps: true })
export class User {
// @Prop({ type: mongoose.Types.ObjectId })
_id: string
@Prop({ required: true })
name: string
@Prop({ required: true, unique: true })
email: string
@Prop({ select: false })
password: string
}
export const UserSchema = SchemaFactory.createForClass(User)
export type AddressDocument = Address & Document
@Schema({ timestamps: true })
export class Address {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })
user: User
@Prop()
line1: string
@Prop()
line2?: string
@Prop()
city: string
@Prop()
state?: string
@Prop()
country: string
}
export const AddressSchema = SchemaFactory.createForClass(Address)
Then I have an AddressService that can fetch addresses for a user:
@Injectable()
export class AddressService {
constructor(@InjectModel(Address.name) private addressModel: Model<AddressDocument>) {}
async save(address: AddressDto): Promise<Address> {
const model = await this.addressModel.create(address)
return model.save()
}
async findAddressForUser(userId: string) {
const userObjectId = new mongoose.Types.ObjectId(userId)
const users = await this.addressModel.find({ user: userObjectId })
}
}
This code has an error: Type '_ObjectId' is not assignable to type 'Condition<User>
I tried passing the userId as a string as well, that did not work either.
What is the right way to query a collection using a reference Id from another collection?
An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running.
Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command.
_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.
I think the user
field shouldn't be of type User
, despite what the NestJS docs say. It should be of type Types.ObjectId
.
Something like this (with cleaner imports aswell):
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { SchemaTypes, Types, Document } from 'mongoose';
export type AddressDocument = Address & Document
@Schema({ timestamps: true })
export class Address {
@Prop({ type: SchemaTypes.ObjectId, ref: User.name })
user: Types.ObjectId;
...
}
export const UserSchema = SchemaFactory.createForClass(User)
I got this from here.
You could also tell TypeScript that this may be either a string, an ObjectId or a User by declaring it as: user: string | Types.ObjectId | UserDocument;
Not sure if this is the proper way of doing this but this is what I ended up doing to get around that error:
async findAddressForUser(userId: string): Promise<Address[]> {
const query: any = { user: new mongoose.Types.ObjectId(userId) }
return await this.addressModel.find(query).exec()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With