首页 > 解决方案 > Mongodb嵌套填充

问题描述

我在 MongoDB 中有 3 个具有以下架构的集合:

 const userSchema = new Schema({
    firstname: {
        type: String,
        trim: true
    },
    surname: {
     type: String
    }
})
userSchema.virtual('products', {
    ref: 'product',
    localField: '_id',
    foreignField: 'user'
})

userSchema.virtual('carts', {
    ref: 'cart',
    localField: '_id',
    foreignField: 'user'
})
const User = mongoose.model('user', userSchema)

-----------

const Product = mongoose.model('product', {
    title: {
       type: String,
       required: true
    },
    description: {
        type: String,
        required: true
    },
    quantity: {
        type: Number,
        default: -1
    },

    user: {
       type: Schema.Types.ObjectId,
       ref: 'user',
       required: true
    }
 })

--------

const ItemSchema = new Schema({
    session_id: {
        type: String
    },
    quantity: {
        type: Number,
        required: true
    },
    price: {
        type: Number
    },
    total: {
        type: Number
    },
    product: {
        type: Schema.Types.ObjectId,
        ref: 'product',
        required: true
    }
})

const CartSchema = new Schema({
    items: [ItemSchema],
    user: {
        type: Schema.Types.ObjectId,
        ref: 'user',
        required: true
    },
    total_price: {
        type: Number,
        default: 0
    }
})
const Cart = mongoose.model('cart', CartSchema)

因此,假设我们在这些集合中有一些数据,我想获取一些用户的购物车数据,如下所示:

user = await User.findById(user_id).populate({
        path: 'carts',
        populate: {
            path: 'products',
            model: 'product'
        }
    })
return user.carts

我收到以下回复,但未提供产品详细信息:

[
    {
        "total_price": 10,
        "_id": "5ff373073b92a40898c50508",
        "items": [
            {
                "_id": "5ff4d3b86404131811e392ef",
                "product": "5fe9ea426c3ff17b383dd599",
                "quantity": 5,
                "price": 2,
                "total": 10,
                "createdAt": "2021-01-05T21:01:44.269Z",
                "updatedAt": "2021-01-05T21:01:44.269Z"
            }
        ],
        "user": "5fe255a5543b7420c9c29c8b",
    }
 ]

怎么可能也获得产品细节,我对集合的结构是否正确?谢谢

标签: node.jsmongodbmongoosemongoose-schemamongoose-populate

解决方案


尝试这个:

 const userSchema = new Schema({
    firstname: {
        type: String,
        trim: true
    },
    surname: {
     type: String
    },
    product: {
        type: Schema.Types.ObjectId,
        ref: 'product',
    },
    cart: {
        type: Schema.Types.ObjectId,
        ref: 'cart',
    })

对于您要实现的目标,虚拟机应该不是必需的。

在 Mongoose 中,虚拟是一种不存储在 MongoDB 中的属性。虚拟通常用于文档上的计算属性。

您需要的一切都存储在数据库中,您无需计算任何东西。


推荐阅读