1

i have a serious problem in updating my data . i have no idea how i can update a specific field in an object of an array in my document .

here is my Schema model :

var shiftSchema = new Schema({
Phone: String,
final: Boolean,
statusSH: String,
order: {
    startTime: String,
    finishTime: String,
    income: String,
    orders: [{
        stat: String,
        orderId: String,
        customerPhone: String,
        orderQuantity: String,
        orderCost: String,
        orderCondition: String,
        orderTag: String
    }]
}
});

when i use "find" it gives me the document and not just the object.

now how can i edit "stat" by finding "orderId" ?

Note that i do not have the index of the object that i want to update and i can just use "find"or "findOne".

i search all over the web and i couldn't find a good guide and example .

sorry for my bad english.

All tips will be appreciated. Thank You.

1 Answer 1

2

You can try to run this query, to update the stat property:

shiftSchema.updateOne({
  'order.orders.orderId': 'id'
}, {
  '$set': {'order.orders.$.stat': 'newStatus'}
})
.then((result) => {
  console.log(result)
}, (e) => {
  console.log(e)
})

You can see I used positional $ operator to access an element in the array and update it without specifying the position of the element (with index).

I also used $set to replace the value of a field.

With just find or findOne you will not make the actual update.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.