Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
adding data to schema optionally in mongodb using node js

I made a 2 mongodb schema in which one is depend on another schema and my both look like this

ownerSchema.js

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

shopSchema.js

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

and this is my add function

const addOwner = async (req, res) => {
 
    const { shopName, shopLocation } = req.body.shopPlace;
    const shop = new Shop({
      shopName,
      shopLocation,
    });
    await shop.save();

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

Problem is sometimes i dont want shopPlace data it should be blank

but I am sending only ownerId, fname, lname from postman it does not saving in my database is there any possible way that if I dont want shopPlace still it should save data to my schema it should be optional

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In your model you can set a default value for shopPlace as follows:

shopPlace : { 
   type: Schema.Types.ObjectId,
   ref: 'Shop',
   default: null
}

So, if you don't provide shopPlace when you create a new Owner, it will be null

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!