[英]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.