TypeError: utils.populate: invalid path. Expected string. Got typeof `undefined`

Viewed 4406

I am trying to use the populate operator of mongoose to merge a product and their users/owners.

I made a "exported" model of the product schema, specifying all fields like so:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const someSchema= new Schema({
  something1: String,
  customers: [{ type: Schema.Types.ObjectId, ref: "customers" }],
  price: Number,
  ...
})
module.exports = mongoose.model("products", someSchema, "products");

I've managed to save the _id from the user/owner in the product and it appears orange as "ObjectId('...')" in MongoDB Compass and this same id matches with a user in the "customers" collection (looking manually).

But when I run the search in another module with:

  const model = require("../../models/productModel");
  model
    .populate("customers")
    .find({ < some fields> })
    .then( ... )
    .catch( ... )

It throws following error in the console:

TypeError: utils.populate: invalid path. Expected string. Got typeof `undefined`

Am I missing something here? I tried for almost an hour and got nothing. Sorry if I missed something crucial, I'm somewhat tired.

Any help is greatly appreciated.

1 Answers

I figured it out.

The problem was that I called populate in the wrong order.

I was calling:

  model
    .populate("customers")
    .find({ < some fields> })
    .then( ... )
    .catch( ... )

But it must be in this order:

  model
    .find({ < some fields> })
    .populate("customers")
    .then( ... )
    .catch( ... )

Because we must first find the documents in order to populate them, otherwise it wouldn't make any sense.

Also for future reference, if you only specify .populate("customers"), it will not fill all ID fields magically, you must specify which field too. You do that with:

.populate({ path: "key_to_fill", model: "customers" })

And now it will replace key_to_fill with the document found in customers.

Other parameters and options you can find here: https://mongoosejs.com/docs/populate.html (Official documentation)

Related