Let's see how to setup relations in MongoDB to our NodeJs App.

Create a user Model

const getDb = require("../helper/database").getDb;
const mongoDb = require("mongodb");

class User {
  constructor(userName, email) {
    this.name = userName;
    this.email = email;
  }

  save() {
    const db = getDb();

    return db
      .collection("users")
      .insertOne(this)
      .then((result) => {
        console.log("result=> " + result);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  static findById(id) {
    console.log("print id->" + id);

    const db = getDb();

    return db
      .collection("users")
      .findOne({ _id: new mongoDb.ObjectID(id) })
//here  we convert the incoming it to bson type
      .then((user) => {
        return user;
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

module.exports = User;



in APP.js

app.use((req, res, next) => {
  User.findById("5eb65dccca1bed06a47f9be0")
//I created a dummy user. and this is his id
    .then((user) => {
      req.user = user;

      next();
    })
    .catch((err) => {
      console.log(err);
    });
 
});

in controller

when creating a new product, we pass the user id also

exports.postAddProduct = (req, res, next) => {
 
  const product = new Product(
    //null,
   // title, //insert values as req.body.title
    //price,
    //description,
    //imgUrl,
    req.user._id
  );

  product
    .save()
    .then((result) => {
      console.log("Succsfully addeddd..!!!!");
      res.redirect("/");
    })
    .catch((err) => {
      console.log(err);
    });
};

In Product Model -> constructor

constructor(_id, title, price, description, imgUrl, userId) {
    this.title = title;
    this.price = price;
    this.description = description;
    this.imgUrl = imgUrl;
    this._id = _id ? new mongoDb.ObjectID(_id) : null;
    this.userId = userId;
  }