node.js - 在 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
});
});
});
解决方案
使用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" }
])
推荐阅读
- json - Swift - Decodable 无法使用可选值解码
- image - 如何使用ffmpeg从每秒1张图像的图像制作视频文件?
- apache-kafka - 卡夫卡 csv 处理
- firebase - 如何观察 Firebase Storage 对象的 downloadUrl 变化?
- javascript - 如何将 flask-wtforms 与 AJAX 正确集成以动态添加字段?
- java - 我不知道如何关联 2 个数组之间的位置
- java - 即使应用程序关闭,如何播放音乐?
- java - 在 MMapDirectory 中找不到段*文件
- python-3.x - 如何在 sqlite3 Python 中获取另一个表的 id
- python - 数据框到 dict