'Mongoose relationships doesn't work when i reference the Order

So I'm kinda new to Mongoose and Mongodb and having a hard time understanding how relationship works, for example I have an Image model that points with an Object Id to an Order, and what I need to do fetch all images that point to that specific order.

So my question is do I need to reference all images to the order to?

Here is my scheema: Image:

const { Schema, model, Types } = require('mongoose');
const ImageSchema = new Schema(
  {
    name: { type: String },
    type: { type: String },
    source: { type: String },
    belongsTo: {
      type: Types.ObjectId,
      ref: 'order',
      default: null,
    },
  },
  { timestamps: true }
);

module.exports = model('Image', ImageSchema);

And here is my Order:

const { Schema, model, Types } = require('mongoose');

const OrderSchema = new Schema(
  {
    id: {
      type: String,
      unique: true,
    },

    status: {
      type: String,
      default: 'draft',
      enum: ['draft', 'new', 'created', 'invoiced', 'paid'],
    },

    visibility: {
      type: Boolean,
      default: true,
    },

    new_km: {
      type: String,
      default: null,
    },

    working_hours: {
      type: Array,
      default: [],
    },

    parts: {
      type: Array,
      default: [],
    },

    total: {
      type: String,
      default: '0',
    },

    othersTotal: {
      type: String,
      default: '0',
    },

    partsTotal: {
      type: String,
      default: '0',
    },
  },
  {
    timestamps: true,
  }
);

module.exports = model('Order', OrderSchema);

So for example now I want to fetch all the orders and populate them with images each order has?:

router.get('/all', passVerify, async (req, res) => {
  try {
    const orders = await Order.find({}).populate([
      { path: 'image', model: 'Image' },
    ]);

    if (orders)
      res.status(200).send({
        success: true,
        data: orders,
      });
    else
      res.status(404).send({
        success: false,
        message: 'Something went wrong fetching the orders.',
      });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: error,
    });
  }
});

This all brings me errors.

I would like to know how to fix and how they work in real.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source