How do I add object list type without relational

Hello,

I’m trying to create a complex schema with mongoose. Some values ​​should be a list of objects, but visible directly on the fields screen (not related). Because this object list must be added as required.

 const schema = Mongoose.Schema({
    'name': { type: String, required: true },
    'images': [{
      'assetType': String,
      'url': String,
      'quality': Number,
    }],
  }, {
    timestamps: false,
  });

Screenshot 2022-12-03 at 05.15.55

If I add it like this, it is added as related. I can add equipment without adding images.

Is there any solution?

EDIT:

 'images': {type: [{
      'assetType': String,
      'url': String,
      'quality': Number,
  }], required: true}

Defining images like this doesn’t work. Again, I can add equipment without adding images.

This question is a more difficult question than it seems.

About setting a validation rule in mongoose to ensure that the array is never empty sure.
It can be done using a custom validator (from mongoose doc)

new mongoose.Schema({
  name: { type: String, required: true },
  images: {
    type: [{ assetType: String, url: String, quality: Number }],
    validate: {
      validator: v => v.length > 0,
      message: 'At least one image is required',
    },
  },
})

But then the issue is that:

  • The forest admin interface is not very convenient for that use case: lists always appear in related records
  • When creating a record, users will need to
    • fill the detail form
    • then go to related and add pictures
    • then go back to the detail page and save (there is no save button on the related page)
  • mongoose validators don’t run on updates by default, so the issue is only half-solved

And then, asking users to upload images manually by entering URLs does not seem very convenient.

We have a widget that allows multi-file-upload that would appear.
Why not create a smartfield using it and let users uploads files directly from it in the details page?

I don’t know which agent you are using (either forest-express-mongoose, or the more recent agent that we released in July), but can point you to documentation

1 Like