Reputation: 5150
When making a collection in mongo to link collection is there any special type I need to use other than just string for the foreign key?
In the example below I am trying to establish a link between two users where the userId
is following the followingId
, I intend to create 1 document for each relation.
import * as mongoose from 'mongoose';
import { Document, Schema } from 'mongoose';
interface FollowingModelInterface extends Document {
followingId: string; // <---- this will be the _id from the users table
userId: string; // <---- this will be the _id from the users table
}
const followingSchema: Schema = new Schema(
{
followingId: { type: String, index: true }, // <----- is the type string correct?
userId: { type: String, index: true }, // <----- is the type string correct?
},
{
timestamps: true,
}
);
const followingModel = mongoose.model<FollowingModelInterface>('Following', followingSchema);
export { followingModel, FollowingModelInterface };
I will use this table to search for all the users that the userId
is following, I will want to get more than just the followingId
back, I will need the users name
and imageid
from the user's collection
Upvotes: 0
Views: 1129
Reputation: 3850
Your type of your foreign key should match the type of the key from the foreign document.
If you've not changed this it will most likely be an ObjectId
.
You can then declare it as:
followingId: { type: mongoose.Types.ObjectId, index: true }
Upvotes: 1