Reputation: 157
I have been trying to update the order status uisng nodejs and mongoose. But i came to problem on updating the status.
I have been trying to access the cart from ORDER document (table). I want to change the status inside cart from 'packed' to 'shifted'. I have been trying all day long but could not find the solution. Please help me with it. How can i select the cart and change the status in mongoose using nodejs?
ORDER
{
"_id": {
"$oid": "60a9a8b2bc65933bb4c22a3b"
},
"cart": [{
"_id": {
"$oid": "60a8bcafe7815c2950de4b28"
},
"userId": "60a3ad7fb51de12a5472de37",
"count": "1",
"status": "packed",
"__v": 0
}],
"userId": "60a3ad7fb51de12a5472de37",
"fName": "jay sree",
"street": "5th cross hindurous",
}
MODEL
const mongoose = require('mongoose')
const schema = mongoose.Schema
const orderSchema = new schema(
{
userId: {
type: String,
required: true
},
cart: [{
type: Object
}],
fName: {
type: String,
required: true
},
street: {
type: String,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Order", orderSchema)
Controller
exports.postUpdateStatus = (req, res, next) => {
let status = req.params.status //shifted
let productId = mongoose.Types.ObjectId(req.params.productid )//60a8bcafe7815c2950de4b28
let orderId = mongoose.Types.ObjectId(req.params.orderid )//60a9a8b2bc65933bb4c22a3b
Order.find({id: orderId})
.select({ cart: {$elemMatch: {id: productId}}})
.then(product => {
res.jsonp(product)
})
.catch(err => {
console.log(err)
})
}
Upvotes: 2
Views: 555
Reputation: 24565
You can call the findOneAndUpdate
function and use the positional operator to update the matching cart-item. Something like:
Order.findOneAndUpdate({
"_id": "60a9a8b2bc65933bb4c22a3b",
"cart._id": "60a8bcafe7815c2950de4b28"
}, {
"$set": {
"cart.$.status": "shifted"
}
}, {
new: true
});
Note that I'm using the new
-option here, in order for findOneAndUpdate
to return the updated document.
Here's an example on mongoplayground where you can play around with the query: https://mongoplayground.net/p/5sW7NB1mJK7
Upvotes: 2