【问题标题】:Extract data from a mongoose object从猫鼬对象中提取数据
【发布时间】:2022-09-27 15:52:45
【问题描述】:

我有一个店铺模型

const Shop = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  shop_name: { type: String },
  products: {_id: mongoose.Schema.Types.ObjectId,type:Array},
});

和产品架构

const Product = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  title: { type: String },
  description: { type: String },
  shop: { type: mongoose.Schema.Types.ObjectId, ref: \"Shop\" },
});

我正在尝试访问 Shop 模型的 products 数组中的产品,以便我可以更新它。

我在网上看了很多,但找不到我要找的东西。我需要使用给定的参数访问 products 数组中的一个非常具体的产品,这些参数是商店的 id 和产品的 id。

这就是我试图做的

const item = await Product.findOne({_id} , \'products\').find({\"products._id\" : productId})

但是,如果第二个 find 方法匹配,它会给出一个 mongoose 对象

[
  {
    products: [ [Object] ],
    _id: 617f1bca39a5a43c1a981060,
    butik: \'scsbutik\',
    butik_slug: \'egzbutikcom-1000010\',
    butik_image: \'https://webizade.com/bm/img/butik-10.jpg\',
    butik_points: \'9.8\',
    butik_order_count: 45,
    butik_success_order_count: 42,
    butik_refund_count: 3,
    is_butik_refund: true,
    __v: 0,
    login: []
  }
]

我需要访问 products 数组中的对象并更新该产品。

提前感谢任何帮助。

    标签: node.js mongodb rest express mongoose


    【解决方案1】:

    默认情况下不要使用 _id 格式我建议声明一个不同的值,然后使用填充方法你可以做到

    const Product = mongoose.Schema({
    shopId: mongoose.Schema.Types.ObjectId,
    title: { type: String },
    description: { type: String },
    shop: { type: mongoose.Schema.Types.ObjectId, ref: 'Shop' },
     });
    

    然后路由

    const item = await Product.find(_id).populate('shopId')
    

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 2019-07-06
      • 2015-12-28
      • 2021-05-06
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      相关资源
      最近更新 更多