How to reference documents in Mongodb

Posted on July 29, 2019
axios
rest API
javascript
reactjs
nodejs
1244

This article is helpful for those who are seriously looking and finding the usecase of reference documents in MongoDB. Referencing comes when we are saving data to database , that thing we obiously do through axios (Most Popular). Just place the below code inside any router where you want to and check the results.

Saving refs to other documents works the same way you normally save properties, just assign the _id value:

let Team = require('./team.model');
let Player = require('./player.model');

const team = new Team({
    _id: new mongoose.Types.ObjectId(),
    Name: 'KoderPlace',
    Logo: 'Log1',
  });
  team.save(function(err) {
    const player = new Player({
      Name: 'Koder1',
      Team: team._id, // This is must while referencing
      ProfilePic: 'Pic1'
    });
    player.save(function(err) {
      console.log('player Added');
    });
    console.log('team Added');
  });

Before Running the above code, you need to have two schemas one for the Team and one for the Player.

Try to write the models in same file or in seperate files as you want.

Team Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Team = new Schema({
  _id: Schema.Types.ObjectId,
  Name: String,
  Logo: String,
});
module.exports = mongoose.model('Team', Team);

Player Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let Player = new Schema({
  Team: { type: Schema.Types.ObjectId, ref: 'Team' },
  Name: String,
  ProfilePic: String,
});

module.exports = mongoose.model('Player', Player);

The results  will be stored in the database (Check the below images for the proof). These results are captured in MongoDB Compass Community GUI. You can check the documents through command line as well.




0 comments

Please log in to leave a comment.