'Foreign Key relationship in Mongoose with customized key

I am kinda new to MongoDB and nextjs space. I have 2 schemas :

  1. User
  2. Fav Dishes

Schema for user is :

import mongoose from 'mongoose' require('mongoose-type-url');

const UserSchema = new mongoose.Schema({
            name: { type: String, unique: true}
            address: {type: String},
       },{ timestamps: {} })
UserSchema.pre("save", function (next) {
let brand = this;
user.name = user.name.replace(/ /g,"_")
next();
})

Another schema is

const FavDish = new mongoose.Schema({
              name: String,
              user: {type: mongoose.Schema.Types.ObjectId, ref : 'User'})

So the reference in FavDish collection want to use is userName instead mongo created ObjectID. and while populating the data for FavDish get the details for user as well. How can i achieve this? please help me.



Solution 1:[1]

So, first of all, if the relationship between the Schemas are 1to1, consider embedding the favDish inside the user Schema and not referencing (each user has a name, an address and a favDish name).

So the userSchema will look like:

  const UserSchema = new mongoose.Schema({
        name: { type: String, unique: true}
        address: String,
        fevDish: String
   },{ timestamps: {} })

If you want to keep it like the way you wanted (with two schemas and referencing) you will need to populate after finding the fevDish:

const populatedDish = await FavDishModel.findOne({name: 'pasta'}).populate('user');
/** 
*  populatedDish - {
*    name: 'pasta',
*    user: {
*      name: 'Justin',
*      address: 'NY'
*    }
*  }
*
*/

this way while finding the dish you want, mongoose will put the user object instead of the _id of it.

Hope that helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1