node.js - 如何选择 Mongoose 中的对象数组?

标签 node.js database mongoose

我一直在尝试使用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/

相关文章:

java - 为什么数据库中的所有数据都没有显示到我的 JTextfield 上

node.js - Mongodb 时间戳非常不准确 - mongoose

javascript - 如何在保存另一个文档之前等待循环完成?

javascript - 我在我的 Node.js 应用程序中使用 MongoSkin,在一段时间不活动后,它失去了与数据库的连接

mysql键/值存储问题

node.js - 如何在实时 gps 跟踪应用程序中使用 node.js?

mysql - 如何从表中获取2个字段中的一些

javascript - res.redirect 在表单提交后显示旧信息?

javascript - 使用Webpack拆分出一个模块,以便在WebWorker中加载

node.js - Azure 函数的 Node 和 DirectlineJS es6 导出的版本兼容性问题