After checking out the
official documentation
[1], I am still not sure on how to create methods for use within mongoose to create & update documents.
So how can I do this?
I have something like this in mind:
mySchema.statics.insertSomething = function insertSomething () {
return this.insert(() ?
}
From inside a static method, you can also create a new document by doing :
schema.statics.createUser = function(callback) {
var user = new this();
user.phone_number = "jgkdlajgkldas";
user.save(callback);
};
ACCEPTED]
Methods are used to to interact with the current instance of the model. Example:
var AnimalSchema = new Schema({
name: String
, type: String
});
// we want to use this on an instance of Animal
AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
return this.find({ type: this.type }, cb);
};
var Animal = mongoose.model('Animal', AnimalSchema);
var dog = new Animal({ name: 'Rover', type: 'dog' });
// dog is an instance of Animal
dog.findSimilarType(function (err, dogs) {
if (err) return ...
dogs.forEach(..);
})
Statics are used when you don't want to interact with an instance, but do model-related stuff (for example search for all Animals named 'Rover').
If you want to insert / update an instance of a model (into the db), then methods are the way to go. If you just need to save/update stuff you can use the save function (already existent into Mongoose). Example:
var Animal = mongoose.model('Animal', AnimalSchema);
var dog = new Animal({ name: 'Rover', type: 'dog' });
dog.save(function(err) {
// we've saved the dog into the db here
if (err) throw err;
dog.name = "Spike";
dog.save(function(err) {
// we've updated the dog into the db here
if (err) throw err;
});
});
dog.save() from within a method? - Industrial
this.save(), since this would refer to dog - alessioalex
return this.model('Animal').find({ type: this.type }, cb); I've never understood why we have to use model('Animal') here, as we are adding this method to the Animal schema. Presumably it's optional then - do you know why it's written like this in the docs? - UpTheCreek
mongoose.model('Animal', AnimalSchema) to register the schema and then later in your code elsewhere mongoose.model('Animal') to grab the model again. When you add something to the model you add it to the schema like AnimalSchema.methods.isCat or AnimalSchema.statics.findAllDogs. - alessioalex
Don't think you need to create a function that calls .save(). Anything that you need to do before the model is saved can be done using .pre() [1]
If you want the check if the model is being created or updated do a check for this.isNew()
[1] http://mongoosejs.com/docs/middleware.html
thiswithin a mongoose query, it'll point thethisof this query, not thethisof the static instance. That was my problem. - Zachary Dahan