首页 > 解决方案 > 在 mongoose 中检索子文档并在 html 页面中显示

问题描述

我正在使用 nodejs 和 mongoose 创建一个购物网站。我想从用户模式中检索用户购物车。

var Products = new Schema(
{
   name: {type: String, required: true},
   details: {type: String, required: true},
   category: {type: String, required: true},
   price: {type: Number, required: true},
   proimg: {data: Buffer ,type: String}
});

var usercart = new Schema({
   productId: {type: String, required: true}
});

var Users = new Schema({
   name: {type: String, required: true},
   email: {type: String, required: true,unique:true,trim:true},
   password: {type: String, required: true},
   address: {city:String,state:String},
   phone: {type: Number, required: true,unique:true},
   cart: [usercart]
});

我希望将所有产品 ID 存储在 usercart 中,并希望存储产品模式中所有产品的详细信息。我不知道如何检索子文档,所以请帮忙。

app.get('/view-cart',function(req,res){
sess=req.session;
user.find({_id: 'sess.id'},'cart',function(err,usr){
   pro=usr.cart;
        console.log(pro);
        //
        // 
        //


        if(err) console.log("Error");
        else  res.render('view-cart', {
            "list" : pro
        });

});
});

标签: node.jsmongoose

解决方案


使用mongodb 3.6 及更高版本,您可以轻松加入嵌套字段,而无需使用$unwind. 我不确定结果,但您可以尝试以下操作:

db.products.aggregate([
  { "$lookup": {
    "from": "usercard",
    "let": { "product_id", "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$productId", "$$product_id"] }}},
      { "$lookup": {
        "from": "users",
        "let": { "cardId", "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": ["$cart", "$$cardId"] }}}
        ],
        "as": "cart"
      }}
    ],
    "as": "cart"
  }},
  { "$unwind": "$cart" }
])

推荐阅读