【问题标题】:Retrieving subdocument in mongoose and showing in html page在 mongoose 中检索子文档并在 html 页面中显示
【发布时间】:2019-04-08 03:24:21
【问题描述】:

我正在使用 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 存储在用户购物车中,并希望存储产品架构中所有产品的详细信息。我不知道如何检索子文档,所以请帮忙。

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.js mongoose


【解决方案1】:

使用mongodb 3.6 and above,您可以轻松加入嵌套字段,而无需使用$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" }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多