简体   繁体   English

如何使用nodejs在mongodb中的两个不同集合中搜索值

[英]how to search for values in two different collections in mongodb using nodejs

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)
})

}) })

I have some products in one collection and the price is in other collection.when I had inserted product unique id with price but when I call more than one product with their price with forEach loop.At that time the value of the product and price goes different many times.I think this is synchronisation problem.what should I for this?? 我在一个集合中有一些产品,而价格在其他集合中。多次不同。我认为这是同步问题。为此我应该做什么?

You can do everything in one query, if you already have the category the query on Category model is not needed: 您可以在一个查询中完成所有操作,如果您已经有了类别,则不需要在类别模型上进行查询:

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"
        },
    ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用nodejs在整个集合中搜索(mongodb) - Search in whole collection(mongodb) using nodejs 使用mongodb嵌入集合 - Embed the collections using mongodb 如何将Elastic Search与Meanjs(Mongodb,Express,Angular,Nodejs)集成 - How to integrate Elastic Search with Meanjs (Mongodb ,Express,Angular,Nodejs) 从两个集合中选择数据mongodb - select data from two collections mongodb 在AngularJS,NodeJS,MongoDB,Mongoose和ExpressJS中以单一表单发布到多个集合 - Posting to multiple collections with a single form in AngularJS, NodeJS, MongoDB, Mongoose, and ExpressJS 如何在春季使用Mongotemplate或MongoRepository从两个集合中获取数据 - How to get data from two collections in spring using Mongotemplate or MongoRepository 如何在Mongoose中合并两个集合并使用createdDate对它们进行排序 - How to combine two collections in Mongoose and sort them using createdDate 我如何从角度控制器发送数组值到节点,并使用该数组值我必须从mongoDB搜索结果 - How do i send array values from angular controller to node and using that array values i have to search result from mongoDB 在两个不同的页面中使用角度控制器的值 - Using Values of an Angular Controller in Two Different Pages 如何使用nodejs将图像上传到文件夹并将路径保存到mongodb? - how to upload the image to folder using nodejs and save the path into mongodb?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM