When to save a mongoose model
Posted
by
kentcdodds
on Stack Overflow
See other posts from Stack Overflow
or by kentcdodds
Published on 2013-11-03T03:48:15Z
Indexed on
2013/11/03
3:53 UTC
Read the original article
Hit count: 176
This is an architectural question. I have models like this:
var foo = new mongoose.Schema({
name: String,
bars: [{type: ObjectId, ref: 'Bar'}]
});
var FooModel = mongoose.model('Foo', foo);
var bar = new mongoose.Schema({
foobar: String
});
var BarModel = mongoose.model('Bar', bar);
Then I want to implement a convenience method like this:
BarModel.methods.addFoo = function(foo) {
foo.bars = foo.bars || []; // Side note, is this something I should check here?
foo.bars.push(this.id);
// Here's the line I'm wondering about... Should I include the line below?
foo.save();
}
The biggest con I see about this is that if I did include foo.save()
then I should pass in a callback to addFoo
so I avoid issues with the async operation. I'm thinking this is not preferable. But I also think it would be nice to include because addFoo
hasn't really "addedFoo" until it's been saved... Am I breaking any design best practices doing it either way?
© Stack Overflow or respective owner