Reputation: 1415
I have a schema with embedded document as below.
const ParentSchema = new Schema({
field: String,
items: [
{
field: String,
field2: Number,
field3: Number
}
]
});
I want to insert a sub document (into items field) and get the last inserted sub document. (Because I need the objectId of that sub socument).
I can implement it as below.
Parent.updateOne(
{ _id: parentId },
{
$push: {
items: {
field: String,
field2: Number,
field3: Number
}
}
}
)
But this will return a result object not last inserted sub document. For that I may use another query to get last embedded document. I want a optimal solution for this.
Upvotes: 0
Views: 51
Reputation: 11975
You can use findOneAndUpdate
with option new: true
to get the updated document then do something like doc.items[doc.items.length - 1]
to get the inserted sub document without using another query:
let doc = await Parent.findOneAndUpdate(
{ _id: parentId },
{
$push: {
items: {
field: field,
field2: field2,
field3: field3
}
}
},
{ new: true }
);
console.log(doc.items[doc.items.length - 1]);
Upvotes: 1