1
votes

I'm somewhat new in what is related to Mongoose and I came to this behaviour I consider as strange. The document returned by Mongoose has fields that are not present in the actual MongoDb document, and seem to be added by Mongoose based on the schema.

I use a schema similar to this (this one is simplified) :

const ProfessionalSchema = new mongoose.Schema({

    product: {
       details: [{
            _id: false,
            id: String, // UUID
            name: String,
            prestations: [{
                _id: false,
                id: String, // UUID
                name: String,
                price: Number,
            }],
        }],
    },
[...]

My document as shown in Mongodb with mongo CLI utility doesn't have a product field.

What I don't understand is why the result of Professional.findById().exec() returns a document with a product:{details[]} field. I expect not to have that field in the Mongoose returned result, since it is not present in the original MongoDb document. The Mongoose documentation found https://mongoosejs.com/docs/guide.html (Schema and Model paragraph) didn't help.

My business logic would require that field not to be present, instead of being forced by the schema. Is this achievable ?

1
Try taking a look at the default option. You could e.g. default your product to null and then, in your business logic, handle the "product is null" case rather than the "product field does not exist" case. As for why this is happening, it's because you're dealing with a schema. If the field doesn't exist on the document, it's going to be auto-populated. The whole point of a schema is to ensure consistency of your document structure. - B. Fleming
@B.Fleming, thank you. I'm new to MongoDb, and I must admit that having a schema-less nature of MongoDb combined with Mongoose which is schema-orientated is quite confusing. Your suggestions seems pretty decent to me. What about posting this comment as an answer ? - SCO
Yeah, taking on both of those at once is definitely confusing. I wasn't 100% sure if this would be a sufficient answer for you, so I submitted it as a comment. I'll be sure to submit a proper answer :) - B. Fleming

1 Answers

2
votes

Try taking a look at the default option. You could e.g. default your product to null and then, in your business logic, handle the "product is null" case rather than the "product field does not exist" case.

As for why this is happening, it's because you're dealing with a schema. If the field doesn't exist on the document, it's going to be auto-populated. The whole point of a schema is to ensure consistency of your document structure.