Mongoose document: Access a field that doesn't exist in the Schema #15264
|
Hi, I want to access a field that doesn't exist in the schema, when I const doc = await MyModel.findById(id);
console.log('doc', doc); // the field appears
console.log('myField', doc.get('myField')); // the field appears
console.log('myField 2', doc.myField) // undefined |
Replies: 3 comments
|
This is expected behavior due to Mongoose's strict mode (enabled by default). When you access Solutions: 1. Add the field to your schema (recommended): const schema = new Schema({ myField: Schema.Types.Mixed });2. Disable strict mode (allows any field to be stored and accessed): const schema = new Schema({ ... }, { strict: false });3. Convert to a plain object first: const plain = doc.toObject();
console.log(plain.myField); // works4. Use const doc = await MyModel.findById(id).lean();
console.log(doc.myField); // worksThe |
|
@Sumit-Mayani is right in general. |
|
Thanks for the clarification, @vkarpov15! To correct my solution #2: For reading a field that exists in DB but not in schema, the correct approaches are:
|
This is expected behavior due to Mongoose's strict mode (enabled by default).
When you access
doc.myFieldvia dot notation, Mongoose only exposes paths defined in your schema. Paths not in the schema returnundefined. However,doc.get("myField")uses an internal getter that reads directly from the underlying document data, bypassing schema restrictions — which is why it works.Solutions:
1. Add the field to your schema (recommended):
2. Disable strict mode (allows any field to be stored and accessed):
3. Convert to a plain object first: