Home > Back-end >  How to add refrence and data in another scheme in mongoose
How to add refrence and data in another scheme in mongoose

Time:09-17

I'm building a Mongoose schema for a store

I have two schema owner and shop I am trying to add data in show with ref as owner but dont know how to do it

here is my schema structure

const mongoose = require("mongoose");

var shopSchema = Schema({
    location  : String,
    startDate : Date,
    endDate   : Date
});

var ownerSchema = Schema({
    fname     : String,
    lname     : String,
    shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }]
});


var Shop  = mongoose.model('Shop', shopSchema);
var Owner = mongoose.model('Owner', ownerSchema);

so this is how my schema look like and I am trying to add detail of owner and shop but don't know how to do it if it is single schema I can easily do it but with ref I can't

const Owner = require("../models/ownerSchema");

const addTask = async (req, res) => {
    let newOwmer = new Owner(req.body);
    try {
    newOwner = await newOwner.save();
    cosnole.log("Added Successfully");
  } catch (err) {
    console.log(err);
  }
};

I can add easily but dont know how to add shop

CodePudding user response:

You would have to do something like this

const mongoose = require("mongoose");

var ownerSchema = Schema({
  fname     : String,
  lname     : String,
  shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }]
});
var Owner = mongoose.model('Owner', ownerSchema);

var shopSchema = Schema({
    location  : String,
    startDate : Date,
    endDate   : Date,
    owner: Owner
});

var Shop  = mongoose.model('Shop', shopSchema);

Then when you create a shop, create an owner first, and add the owner at the creation of a shop. Maybe like this

// Import your shop and owner models
const fetchedOwner = await Owner.get('the-owner-id')
const createShop = {
  location  : 'London'
  startDate : 'some date'
  endDate   : 'another date'
  owner: fetchedOwner
}
await Shop.create(createShop)
  • Related