[英]MySQL select values from one table based on array of ids from another table
[英]getting values of array of ids from another table
我是節點數據庫和noSQL數據庫的新手,並且在理解如何傳遞ID數組並使用另一個表中的ID查找值時遇到了麻煩。 我有兩個表“用戶”和“產品”。 “用戶”表如下所示:
{
"_id":ObjectId("54925687fd6s87f6dsf8"),
"products":[ObjectId("fdsfdsa33f"),ObjectId("fdsa4grf4g6"), etc..]
}
產品表類似:
{
"_id":ObjectId("fdsfdsa33f")
"color":red
"size":large
}
我想了解如何獲取ID在users.products數組中的產品的值,並通過路由將其發送到我的Jade模板中。 提前致謝!
現在我可以做到,但是一次只能使用
router.get('/dashboard', utils.requireLogin, function(req, res) {
models.Product.findOne({ _id: req.user.product[2] }, 'color size', function(err, doc) {
if(err){return console.error(err)}else{
console.log(doc.name);
var prop = doc.name;
res.render('dashboard.jade', {prop : prop});
}
});
});
還有我的玉器文件:
block body
.container
.col-md-6
h1 Manage Properties
if user.products.length == 0
p No Products
else
each prod, i in user.products
li #{prop.color}
li #{prop.size}
我知道我必須手動設置陣列號,但想傳遞所有ID並獲取所有產品信息的回調。
我在尋找的SQL等效項將類似於:
for(var i=0; i<user.products.length;i++){
SELECT * FROM products WHERE id = user.products[i]
}
您可以使用Mongoose模型實例的populate方法實現此目的:
router.get('/dashboard', utils.requireLogin, function(req, res) {
models.User
// this assumes the id is stored in user.id
.findOne({ _id: req.user.id })
// populate the 'products' field using the ids in the array
.populate('products')
.exec(function(err, user) {
// The products can be found in the user.products property
user.products;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.