Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mongodb - mongoose .populate() is not populating even with variable set to ObjectId

Here is my model for "product" schema:

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

Here is the router for the GET method:

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 });
  }
});

What I actually get is this:

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

In Mongo Compass I can see that "productCategory" is set with ObjectId value.

Any ideas what am I doing wrong?

Thanks!

question from:https://stackoverflow.com/questions/65836488/mongoose-populate-is-not-populating-even-with-variable-set-to-objectid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you should put the key that has ref to populate like this:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...