How to bypass the alternate syntax for creating subdocument array from an object array in schema?
https://mongoosejs.com/docs/subdocs.html#altsyntax
According to the docs, a schema like:
const MySchema = new Schema({
domain: String,
urls: [{ url: String, position: Number }],
});
Will make my entries created via this schema have a subdocument field urls where each entry has an _id property. This is screwing with my testing.
I just want my schema to enforce that MySchema entries have an array urls with objects that have the properties url:string and position:number, no subdocuments.
How can I achieve this?
You just want to skip _id, right? Just do:
urls: [new Schema({ url: String, position: Number }, { _id: false })],
Skipping _id "works" yes, but is the urls field still populated as a mongoose subdoc with all the associated data? This makes the entry much larger?
Using the above will just omit the _id from being created inside the urls array's objects just as you requested.
If you mean "populated" as in filled/completed with its correct data, then yes, it will have an array of objects with just url and position properties.
If you mean as in mongoose's populate (since you mention associated data and the entry being made much larger), then it is not the case.
I meant populated as in creating the urls field as a subdocument array where each entry is a mongoose subdocument with the associated metadata and methods that are returned with Model.find(). I guess kinda like what https://mongoosejs.com/docs/api.html#model_Model.hydrate does
Considering:
Each subdocument has an _id by default. Mongoose document arrays have a special id method for searching a document array to find a document with a given _id.
It seems essential for the _id to be existing for the methods to be called (how would you for example call parent.children.id(_id).remove(); if you have no _id?)
But I don't want a subdocument array! Just a native object array with some specified/required named fields
If that is the case, then of course.
@upugo-dev there's no way to get built-in Mongoose validation without a subdocument array
@vkarpov15 perfect thanks, that was my conclusion too, sadly for us! What would be the recommended best practice then in our case?
Use a subdocument array in your schema, and use lean when you don't need a fully fledged document array.
Use a subdocument array in your schema, and use lean when you don't need a fully fledged document array.
Thanks. This was what I tried initially, but it seemed as if lean() wasn't working properly, as in the lean() command worked on the parent document, but didn't propagate down to the child/subdoc array - this still returned _id fields. Is there some setting or something you need to apply to make this happen?
What makes you think lean() strips out _id properties? It doesn't do that.
To remove _id properties from subdocument arrays, set the _id: false option:
urls: [new Schema({ url: String, position: Number }, { _id: false })]