I am facing a problem. I have a model named Car
which has the following structure.
{
_id: '6179bd464c68a217e895703c',
salesInfo: {
salesDate: [
{
_id: '6179bd464c68a21fgff5703c',
name: 'John'
}
]
}
}
I want to add multiple new sale dates inside the embedded document named salesDate
and return these newly added sale dates as a response to the frontend something like this.
data: {
salesInfo: {
// want to return only newly added sales date
salesDate: [
{
_id: "6179bd464c1ffffgff5703c",
name: "Doe"
},
{
_id: "6179bd464cf1fgff5703c",
name: "Tim"
}
]
}
}
I am using mongoose
findOneAndUpdate()
method and using $push
operator inside the update query and returning the field salesInfo.salesDate
something like this.
const salesObj = [{ name: "Doe" }, { name: "Tim" }];
const response = await Car.findOneAndUpdate(
{ _id: "6179bd464c68a217e895703c" },
{ $push: { "salesInfo.salesDate": salesObj } },
{
upsert: false,
new: true,
fields: {
_id: 0,
"salesInfo.salesDate": 1,
},
}
);
But it is returning the response with all dates, I only want newly added sale dates. How can I solve this problem?
CodePudding user response:
read response and create your data from node js
const response = await Car.findOneAndUpdate(
{ _id: "6179bd464c68a217e895703c" },
{ $push: { "salesInfo.salesDate": salesObj } },
{
upsert: false,
new: true,
fields: {
_id: 1,
"salesInfo.salesDate": 1,
},
}
);
var tt = []
saleObj.forEach(item=>{
item._id = response._id
tt.push(item)
})
response.saleInfo.saleDate = tt
res.json(response)
CodePudding user response:
Try to separate your data. Make a schema for the salesInfo and another for the salesDate and try to make a relation between the two schemas. Or when you do a "findOneAndUpdate" try to use the _id of Car model not the _id of salesDate.