【问题标题】:Get parent data based reference ID on Node.js and MongoDB在 Node.js 和 MongoDB 上获取基于父数据的引用 ID
【发布时间】:2020-09-07 05:41:45
【问题描述】:

我正在尝试根据orders products id 获取products 数据,以下是我的Order 模型

import mongoose from 'mongoose';

const { ObjectId, String, Number } = mongoose.Schema.Types;

const OrderSchema = new mongoose.Schema({
    user: {
        type: ObjectId,
        ref: "User"
    },
    products: [
        {
            quantity: {
                type: Number,
                default: 1
            },
            product: {
                type: ObjectId,
                ref: "Product"
            }
        }
    ],
    email: {
        type: String,
        required: true
    },
    total: {
        type: Number,
        required: true
    },
    status: {
        type: String,
        required: true,
        default: 'pending',
        enum: ["pending", "delivered"]
    }
},{
    timestamps: true
});

export default mongoose.models.Order || mongoose.model("Order", OrderSchema);

产品型号:

import mongoose from 'mongoose';

const { String, Number } = mongoose.Schema.Types;

const ProductSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    productType: {
        type: String,
        required: true
    },
    sku: {
        type: String,
        unique: true
    },
    description: {
        type: String,
        required: true
    },
    mediaUrl: {
        type: String,
        required: true
    }
},{
    timestamps: true
});

export default mongoose.models.Product || mongoose.model('Product', ProductSchema);

所有订单的查询如下:

const orders = await Order.find()
    .sort({ createdAt: 'desc' })
    .populate({
        path: "products.product",
        model: "Product"
    });
// console.log(orders)
res.status(200).json({ orders });

这个概念是在创建订单时使用产品 ID 创建的,我想根据订单产品 ID 获取产品。

这样就显示出来了

MongooseError [MissingSchemaError]:尚未为模型“产品”注册架构。

我该如何解决?

谢谢

【问题讨论】:

标签: javascript node.js mongodb express


【解决方案1】:

Order 模型中,您可能会导入Product 模型,然后在您使用的ref 中不带引号,例如

ref: Product

我就是这么想的。

谢谢

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2011-04-12
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多