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
CodePudding user response:
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