I am new to node and noSQL databases and am having trouble understanding how to pass an array of id's and find the values using the id in another table. I have two tables 'users' and products'. The 'users' table looks something like:
{
"_id":ObjectId("54925687fd6s87f6dsf8"),
"products":[ObjectId("fdsfdsa33f"),ObjectId("fdsa4grf4g6"), etc..]
}
The products table something like:
{
"_id":ObjectId("fdsfdsa33f")
"color":red
"size":large
}
I would like to understand how I can get the values of only the products whose ID is in the users.products array and send that through a route to use in my jade template. Thanks in advance!
Right now I can do it, but can only get one of the array values at a time using
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});
}
});
});
And my jade file:
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}
I understand I have to manually set the array number but would like to pass all the ids and get a callback of all the product information.
The SQL equivalent of what I am looking for would be something like:
for(var i=0; i<user.products.length;i++){
SELECT * FROM products WHERE id = user.products[i]
}
You can achieve this with the populate method of a Mongoose model instance:
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;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.