You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose关联产品与城市后无法获取DBRef对象的问题求助

MongoDB关联数据无法访问的问题分析与解决

核心错误点及修正方案

1. 城市数据初始化时的异步处理错误

  • Product.find()是异步方法,直接赋值给products得到的是Promise对象,而非实际产品数组,导致products[0]、products[1]无法正确获取产品ID
  • 未提取产品的_id字段,而是直接传递整个产品对象,不符合MongoDB关联字段的要求

修正后的城市初始化代码:

const Product = require('../models/Product');
const Cities = require('../models/City');

const defaultValuesCities = async () => {
    try {
        // 用await等待异步查询完成,获取实际产品数据
        const products = await Product.find();
        if (products.length < 2) {
            console.log("产品数据不足,无法初始化城市关联");
            return;
        }
        // 插入城市数据时,传递产品的_id字段
        await Cities.insertMany([
            {
                name: "Amsterdam",
                products_cost: [
                    {
                        product_id: products[0]._id,
                        price: 150 // 可自定义价格,或使用默认值0
                    },
                    {
                        product_id: products[1]._id,
                        price: 300
                    }
                ],
                shipRoute: 8,
                translations: {
                    Spanish: { name: "Ámsterdam" }
                }
            }
        ]);
    } catch (error) {
        console.log(error);
    }
};

module.exports = { defaultValuesCities };

2. 查询时未正确填充关联数据(Populate)

原代码中populate(products)存在两个问题:

  • products是未定义的变量,需用字符串指定关联路径
  • 关联字段嵌套在products_cost数组内,正确路径应为products_cost.product_id

修正后的路由查询代码:

router.get('', async (req, res) => {
    try {
        // 指定嵌套路径,填充products_cost中的product_id关联数据
        const cities = await City.find().populate('products_cost.product_id');
        res.render('index', { cities });
    }
    catch (error) {
        console.log(error);
    }
});

3. 模板访问逻辑说明

完成上述修正后,EJS模板中的element.product_id会被填充为完整的产品文档,此时可以正常访问产品的name、translations等字段,原模板代码无需修改即可正常运行。


内容的提问来源于stack exchange,提问作者Aglaophot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:05:09