Bilger Yahov
Bilger Yahov

Reputation: 387

Mongoose schema, nested objects with default values

Recently I have started building my own RESTful API using the MEAN stack. So far, so good. Yesterday I bumped into a small issue, which I have been trying to solve, but no successful results have been seen until now...

I have a Mongoose Schema which looks like this:

const hotelSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    stars: {
        type: Number,
        min: 0,
        max: 5,
        "default": 0
    },
    services: [String],
    description: {
        type: String,
        "default": "No description"
    },
    photos: [String],
    currency: {
        type: String,
        "default": "Not specified"
    },
    reviews: [reviewSchema],
    rooms: [roomSchema],
    location: {
        address: {
            type: String,
            "default": "Not specified"
        },
        // Always store coordinates longitude E/W, latitude N/S order
        coordinates: {
            type: [Number],
            index: '2dsphere'
        }
    }
});

And this is how I create the model instance:

 Hotel
        .create({
            name: req.body.name,
            description: req.body.description,
            stars: parseInt(req.body.stars, 10),
            services: _splitArray(req.body.services),
            photos: _splitArray(req.body.photos),
            currency: req.body.currency,
            location: {
                address: req.body.address,
                coordinates:[
                    parseFloat(req.body.lng),
                    parseFloat(req.body.lat)
                ]
            }

Everything works perfect and as expected with a small detail. I am using Advanced Rest Client to make the POST request. It can be seen below:

Request with Rest Client

And this is what I get as a response: Response from Rest Client

So the problem is that, if I do not enter an address, I would like to see the default value as it can be seen in the schema - "Not specified". Unfortunately, I cannot achieve this.

Can you please help me?

Upvotes: 5

Views: 4724

Answers (1)

Bilger Yahov
Bilger Yahov

Reputation: 387

Solved!

Actually it seems that it did work correctly. When I make a GET request to fetch the newly created hotel by id, it actually returns it as I would like to, with "address" set to "Not specified".

The fact that after creating the hotel with Model.create() function, the callback that is returned contains the hotel, but without "address" being "Not specified".

I tried the request with Postman as well, the result is the same - no address set.

But anyway, I see that it actually works. I will try to find why the returned object in the callback is not complete though....

Upvotes: 1

Related Questions