Pranavan
Pranavan

Reputation: 1415

Insert into embedded document and return inserted sub document

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

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

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

Related Questions