uglycode
uglycode

Reputation: 3082

Mongoose - what's going on with the instances of models?

I've noticed this funny thing when instantiating the model in mongoose - the instance can be changed through other means than instance itself. Here's an example:

var articleSchema = new Schema({
    name: 'String',
    price: 'Number'
});

var Article = mongoose.model('Article', articleSchema);

var nexus = new Article({
    name: 'Nexus 5',
    price: 300
});

nexus.save(function(err, instance) {
    instance.name = 'Nexus Five';
    instance.save(function(err, instance2) {
        instance2.name = 'Nexus 5ive';
        instance2.save(function(err, instance3) {
            console.log(nexus.name); //'Nexus 5ive'
        });
    });
});

As you can see in the example I never changed the name property of nexus, I changed the properties of the model that save function returned in the callback. Is it OK to approach changing the data in this way? Or should I just stick to the firstly defined instance (i.e. nexus variable)? It seems a bit confusing, since you can easily lose control on what you're dealing with.

Upvotes: 0

Views: 78

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

The save function returns a model. If you wish you can continue modifying it.

But as the model instance you get back will always be exactly the same as the one you saved, I can't imagine when it would be truly useful not to to just keep mutating the original model. By the same token when would you ever mutate the original document, save it, mutate it again, then save it again? I'm not coming up with any scenarios where I would write the code in your example.

If you call findOneAndUpdate with the new option, suddenly the returned model instance becomes useful, since it's a fresh copy of the document (one which might have been mutated by another client).

Upvotes: 1

Related Questions