【问题标题】:how to search for values in two different collections in mongodb using nodejs如何使用nodejs在mongodb的两个不同集合中搜索值
【发布时间】:2017-07-12 16:58:51
【问题描述】:
router.post('/api/getproductsbycategory', function(req, res){
var category = req.body.category
Category.getCategoryId(category, function(err, categoryId){
    if(err){
        throw err;
    }
    if(categoryId.length){
        Product.getProductByCid(categoryId[0]._id, function(err, product){
            if(err){
                throw err;
            }
            res.json(product)
        })
    }
})

});

router.post('/api/getproductprice', function(req, res){
var product = req.body.id
Productprice.getProductprice(product, function(err, productprice){
    if(err){
        throw err;
    }
    res.json(productprice)
})

})

我在一个集合中有一些产品,价格在另一个集合中。当我插入带有价格的产品唯一 ID 但是当我用 forEach 循环调用多个产品及其价格时。当时产品的价值而且价格多次变化。我认为这是同步问题。我该怎么办??

【问题讨论】:

  • 请分享您的代码。可能是 foreach 循环的问题。
  • 我使用 Angularjs 调用这两个函数。我可以做一些像产品和价格返回数组这样的事情吗?我可以在 Angular 上调用并且我不必从那里调用 @times?

标签: angularjs node.js mongodb


【解决方案1】:

您可以在一个查询中完成所有操作,如果您已经拥有类别,则不需要类别模型上的查询:

Product
.aggregate([
        $match: {
            category_id: YOUR_CATEGORY_ID
        },
        $lookup: {
            from: "Productprice",
            localField: "category_id", //category_id field inside Product model
            foreignField: "category_id", //category_id field inside Price model
            as: "price"
        },
    ])

【讨论】:

  • 但是我的 category、product 和 product price 都是三个不同的集合,我想在其中 3 个集合中获取符合条件的数据。
  • 谢谢你,,,,你能再告诉我一件事,如何为这两个模型创建架构吗?
  • 我的 categoryid 是 objectID 的格式,并且 this id 以字符串的形式保存在产品集合中,例如 (product_id : "665454g415") 类似这样。如何在 mongodb 中匹配这两个值控制台??
  • 分类的字段_id与产品的字段category_id匹配即可
  • 如何在nodejs中使用?如何为此创建架构?
猜你喜欢
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2016-02-28
相关资源
最近更新 更多