【问题标题】:Mongoose find() with multipe values具有多个值的猫鼬 find()
【发布时间】:2019-07-10 00:20:12
【问题描述】:

我正在尝试使用 thisCart 数组从产品集合中查找()多个 id,该数组还有一些我想比较的 id。 我尝试了几种方法都没有成功。

cart.findOne({"user_id": userId, "activeCart": true}).then(thisCart => {
        Product.find({"product_id": prodId})
        // here thisCart bring back arrays with multi ids 
       // which I want to do foreach thisCart[i].id = Product.product_id
       // and eventually get all the products which equal to thisCart[i].id
        res.status(200).json({

        });

【问题讨论】:

    标签: node.js api mongoose


    【解决方案1】:

    首先,因为你使用chart.findOne(...),所以只会返回一个数据。

    像这样尝试async await 和array.map:

    app.get('/your end point', async (req,res) => {
    try{
     const thiChart = await Cart.findOne({"user_id": userId, "activeCart": true});
     const thisProduct = await  Product.find({"product_id": prodId});
     const result = thisProduct.map(item => {
      return item.id = thisChart.id //or may be anything you want
     }) //using array.map will return array
    
     console.log(result) //optional 
    
     res.status(200).json({
      result
     });
    
    } catch (error){
      console.log(error)
      }
     }
    )
    

    希望对你有帮助

    【讨论】:

    • 实际上我使用的是以下内容:NodeJs Mongoose TypeScript Cart 是我使用的模型架构 `` const shoppingCartSchema = mongoose.Schema({ user_id: { type: String, required: true}, cart_date : { type: String, required: true}, activeCart: { type: Boolean, required: true }, cart_content: [{ product_id: { type: String, required: true}, product_quantity: { type: Number, required: true} , }] }) ```
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2015-04-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多