I am trying to update my 2nd schema which having reference in first schema
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 I am trying to update my schema like this
const update = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.fname) update.fname = req.body.fname;
if (req.body.lname) update.lname = req.body.lname;
if (req.body.shopPlace.shopName) update.shopPlace.shopName = req.body.shopPlace.shopName;
if (req.body.shopPlace.location) update.shopPlace.location = req.body.shopPlace.location;
let newOwmer = new Owner.updateOne(
{ ownerId: id },
{
$set: update,
},
{ runValidators: true }
);
};
I am trying to update shop but its not working and where am i wrong i dont know
CodePudding user response:
you shoud run multiple update
const update = async (req, res) => {
const { id } = req.params;
let update = {};
let updateShop = {}
if (req.body.fname) update.fname = req.body.fname;
if (req.body.lname) update.lname = req.body.lname;
if (req.body.shopPlace.shopName) updateShop.shopPlace.shopName = req.body.shopPlace.shopName;
if (req.body.shopPlace.location) updateShop.shopPlace.location = req.body.shopPlace.location;
let newOwmer = new Owner.findOneAndUpdate(
{ ownerId: id },
{
$set: update,
},
{ runValidators: true ,lean:true}
);
// get return doc and get `shopPlace` and run another query
let newShop = new Shop.findOneAndUpdate(
{ _id: id },
{
$set: updateShop,
},
{ runValidators: true ,lean:true}
);
};
CodePudding user response:
const update = async (req, res) => {
const { id } = req.params;
let update = {};
let updateShop = {}
if (req.body.fname) update.fname = req.body.fname;
if (req.body.lname) update.lname = req.body.lname;
if (req.body.shopPlace.shopName) updateShop.shopPlace.shopName = req.body.shopPlace.shopName;
if (req.body.shopPlace.location) updateShop.shopPlace.location = req.body.shopPlace.location;
// get shopPlace _id from Owner
const { shopPlace } = await Owner.findOneAndUpdate(
{ ownerId: id },
{
$set: update,
},
{ new:true}
);
// update shop
let newShop = await Shop.findOneAndUpdate(
{ _id: shopPlace },
{
$set: updateShop,
},
{new:true}
);
};