繁体   English   中英

从另一个表获取ID数组的值

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM