Home > database >  Adding data into two different mongodb Schema using node js
Adding data into two different mongodb Schema using node js

Time:09-16

ownerSchema.js

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

shopSchema.js

var shopSchema = Schema({
    shopName  : String,
    location  : String,
    startDate : Date,
    endDate   : Date
});
var Shop  = mongoose.model('Shop', shopSchema);

So this are my two different schema and I am trying to insert data in this two schema but don't know the exact way as I have wrote a code to add data but for the single schema

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

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

Here i want to know how can I add data via postman I am sending data like this from postman

{
  "fname"     : "tom",
  "lname"     : "Jerry",
  "ShopPlace" : {
                 "shopName" : "Juice Shop",
                 "location" : "Mumbai"
                 }
}

as its showing me this error

owner validation failed: Shop: Cast to ObjectId failed for value

How can i send and store data inside mongodb ?

CodePudding user response:

You first need to create your shop and pass the resulting id to the owner you'd like to create. Here's an example (still needs validation and error handling of course):

// ...
const shop = new Shop({  
  shopName: req.body.ShopPlace.shopName
  location: req.body.ShopPlace.location
});    
await shop.save();

const owner = new Owner({
            fname: req.body.fname, 
            lname: req.body.lname, 
            shopPlace: shop._id
});
await owner.save();

It's described in detail in the offical mongoose-docs: https://mongoosejs.com/docs/populate.html#saving-refs

CodePudding user response:

{
    "fname"     : "tom",
    "lname"     : "Jerry",
    "ShopPlace" : {
        "shopName" : "Juice Shop",
        "location" : "Mumbai"
    }
}

As this is your data, you're sending from postman. So at first you need to separate the Shop & Owner info from this object.

const ownerData = req.body;
const shopData  = ownerData.ShopPlace;
delete ownerData.ShopPlace;

You code is giving error because shop's ID (i.e. shopPlace) is not created before adding it to Owner collection. So, you have to add Shop first then Owner as owner needs shop's id.

const shopPlace = new Shop(shopData);   // This `shopData` is from above step
await shopPlace.save();

ownerData.shopPlace = shopPlace.id;
await Owner.create(ownerData);
  • Related