Ganzo
Ganzo

Reputation: 250

mongoose populate() don't work with find()

I have this 2 schema:

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const categorySchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      required: "Name is required",
      minlength: [2, "Too short"],
      maxlength: [32, "Too long"]
    },
    slug: {
      type: String,
      unique: true,
      lowercase: true,
      index: true
    }
  },
  { timestamps: true }
);

module.exports = mongoose.model("Category", categorySchema);

and

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const subSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      required: "Name is required",
      minlength: [2, "Too short"],
      maxlength: [32, "Too long"]
    },
    slug: {
      type: String,
      unique: true,
      lowercase: true,
      index: true
    },
    parent: {
      type: ObjectId,
      ref: "Category,",
      required: true
    }
  },
  { timestamps: true }
);

module.exports = mongoose.model("Sub", subSchema);

and this controller:

exports.list = async (req, res) =>
  res.json(
    await Sub.find()
      .sort({ createdAt: -1 })
      .exec()
  );

I want to display the name of the category that contains the subcategory before displaying the subcategory name in this react component :

{subs.filter(searched(keyword)).map((s) => (
        <div className="alert alert-secondary" key={s._id}>
          {s.parent.name}
          {s.name}
          <span
            onClick={() => handleRemove(s.slug)}
            className="btn btn-sm float-right"
          >
            <DeleteOutlined className="text-danger" />
          </span>
          <Link to={`/admin/sub/${s.slug}`}>
            <span className="btn btn-sm float-right">
              <EditOutlined className="text-warning" />
            </span>
          </Link>
        </div>
      ))}

but when i update the controller and use populate like that:

exports.list = async (req, res) =>
  res.json(
    await Sub.find()
      .populate('parent')
      .sort({ createdAt: -1 })
      .exec()
  );

nothing is return how i have to use populate to show the parent name before the sub name?

thanks.

Upvotes: 0

Views: 59

Answers (1)

Laurin
Laurin

Reputation: 177

Mongoose populates via the ref field and it seems you have a typo there with "Category," which should be "Category" (notice the extra comma)

Upvotes: 1

Related Questions