即使变量设置为 ObjectId,mongoose .populate() 也不会填充

问题描述

这是我的“产品”架构模型:

const productSchema = new Schema({
  productName: String,productCategory: {
    type: Schema.Types.ObjectId,ref: "category",},productPrice: Number,productImageUrl: String,});

这是 GET 方法的路由器:

router.get("/",async (req,res) => {
  try {
    const products = await ProductModel.find().populate("category");
    res.status(200).json({ erorr: false,products });
  } catch (err) {
    res.status(500).json({ error: true,err });
  }
});

我实际得到的是:

"error": false,"products": [
    {
        "_id": "6009f4bfd397734920c93ce8","productName": "Milk","productCategory": "6009d244332f2f22c40f90b4","productPrice": 8,"productImageUrl":""

在 Mongo Compass 中,我可以看到“productCategory”设置了 ObjectId 值。

知道我做错了什么吗?

谢谢!

解决方法

您应该像这样填充具有 ref 的键:

 const products = await ProductModel.find().populate("productCategory");

,

试试这个:

const mongoose = require('mongoose');
const Types = mongoose.Schema.Types;

const productSchema = new Schema({
  productName: String,productCategory: {
    type: Types.ObjectId,ref: "category",},productPrice: Number,productImageUrl: String,});

 const products = await ProductModel.find({}).populate({path:"productCategory"});

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...