我一直在尝试使用nodejs和mongoose更新订单状态。但我在更新状态时遇到了问题。
我一直在尝试从订单文档(表)访问购物车。我想将购物车内的状态从“已包装”更改为“已转移”。我一整天都在尝试但找不到解决方案。请帮我解决一下。如何使用 NodeJS 选择购物车并更改 mongoose 中的状态?
订单
{
"_id": {
"$oid": "60a9a8b2bc65933bb4c22a3b"
},
"cart": [{
"_id": {
"$oid": "60a8bcafe7815c2950de4b28"
},
"userId": "60a3ad7fb51de12a5472de37",
"count": "1",
"status": "packed",
"__v": 0
}],
"userId": "60a3ad7fb51de12a5472de37",
"fName": "jay sree",
"street": "5th cross hindurous",
}
型号
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)
})
}
最佳答案
您可以调用findOneAndUpdate
函数并使用positional operator更新匹配的购物车商品。像这样的东西:
Order.findOneAndUpdate({
"_id": "60a9a8b2bc65933bb4c22a3b",
"cart._id": "60a8bcafe7815c2950de4b28"
}, {
"$set": {
"cart.$.status": "shifted"
}
}, {
new: true
});
请注意,我在这里使用了new
选项,以便将findOneAndUpdate
设置为return the updated document .
这是 mongoplayground 上的一个示例,您可以在其中使用查询:https://mongoplayground.net/p/5sW7NB1mJK7
关于node.js - 如何选择 Mongoose 中的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67658973/