What is the difference between methods and statics?
Mongoose API defines statics as
Statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.
What exactly does it mean? What does existing directly on models mean?
Statics code example from documentation:
AnimalSchema.statics.search = function search (name, cb) {
return this.where('name', new RegExp(name, 'i')).exec(cb);
}
Animal.search('Rover', function (err) {
if (err) ...
})
Think of a static like an "override" of an "existing" method. So pretty much directly from searchable documentation:
AnimalSchema.statics.search = function search (name, cb) {
return this.where('name', new RegExp(name, 'i')).exec(cb);
}
Animal.search('Rover', function (err) {
if (err) ...
})
And this basically puts a different signature on a "global" method, but is only applied when called for this particular model.
Hope that clears things up a bit more.
It seems like
'method' adds an instance method to documents constructed from Models
whereas
'static' adds static "class" methods to the Model itself
From the documentation:
Schema#method(method, [fn])
Adds an instance method to documents constructed from Models compiled from this schema.
var schema = kittySchema = new Schema(..);
schema.method('meow', function () {
console.log('meeeeeoooooooooooow');
})
Schema#static(name, fn)
Adds static "class" methods to Models compiled from this schema.
var schema = new Schema(..);
schema.static('findByName', function (name, callback) {
return this.find({ name: name }, callback);
});
Related
TL;DR: Is there a safe way to dynamically define a mongoose discriminator at runtime?
I have an app with a MongoDB collection where users have some control over the underlying schema.
I could add one or two fixed, required fields and just use mongoose.Mixed for the remainder that users can change, but I'd like to make use of Mongoose's validation and discriminators if I can.
So, what I've got is a second collection Grid where the users can define the shape they'd like their data to take, and in my main model Record, I've added a function to dynamically generate a discriminator from the definition in the second collection.
The code for my Record model looks like this:
const mongoose = require("mongoose")
const recordSchema = new mongoose.Schema({
fields: {
type: Array,
required: true
}
}, {
discriminatorKey: "grid"
})
const Record = mongoose.model("Record", recordSchema)
module.exports = grid => {
// Generate a mongoose-compatible schema from the grid's field definitions
const schema = grid.fields.map(field => {
if(field.type === "string") return { [field.name]: String }
if(field.type === "number") return { [field.name]: Number }
if(field.type === "checkbox") return { [field.name]: Boolean }
return { [field.name]: mongoose.Mixed }
})
return Record.discriminator(grid._id, new mongoose.Schema(schema))
}
This is inside an Express app, and I use the model in my middleware handlers something like this:
async (req, res) => {
const grid = await Grid.findById(req.params.id)
const Record = await GenerateRecordModel(grid)
const records = await Record.find({})
res.json({
...grid,
records
})
}
This works great on the first request, but after that I get an error Discriminator with name “ ” already exists.
I guess this is because only one discriminator with its name per model can exist.
I could give every discriminator a unique name whenever the function is called:
return Record.discriminator(uuidv4(), new mongoose.Schema(schema), grid._id)
But I imagine that this isn't a good idea because discriminators seem to persist beyond the lifetime of the request, so am I laying the groundwork for a memory leak?
I can see two ways forward:
COMPLICATED? Define all discriminators when the app boots up, rather than just when a HTTP request comes in, and write piles of extra logic to handle the user creating, updating or deleting the definitions over in the Grid collection.
SIMPLER? Abandon using discriminators, just use mongoose.Mixed so anything goes as far as mongoose is concerned, and write any validation myself.
Any ideas?
I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:
We may also define our own custom document instance methods too.
// define a schema
var animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
Now all of our animal instances have a findSimilarTypes method available to it.
And then:
Adding static methods to a Model is simple as well. Continuing with our animalSchema:
// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
return this.find({ name: new RegExp(name, 'i') }, cb);
}
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
console.log(animals);
});
It seems with static methods each of the animal instances would have the findByName method available to it as well. What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?
statics are the methods defined on the Model. methods are defined on the document (instance).
You might use a static method like Animal.findByName:
const fido = await Animal.findByName('fido');
// fido => { name: 'fido', type: 'dog' }
And you might use an instance method like fido.findSimilarTypes:
const dogs = await fido.findSimilarTypes();
// dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
But you wouldn't do Animals.findSimilarTypes() because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.
Similarly you wouldn't¹ do fido.findByName because findByName would need to search through all documents and fido is just a document.
¹Well, technically you can, because instance does have access to the collection (this.constructor or this.model('Animal')) but it wouldn't make sense (at least in this case) to have an instance method that doesn't use any properties from the instance. (thanks to #AaronDufour for pointing this out)
Database logic should be encapsulated within the data model. Mongoose provides 2 ways of doing this, methods and statics. Methods adds an instance method to documents whereas Statics adds static “class” methods to the Models itself.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:
const bookSchema = mongoose.Schema({
title: {
type : String,
required : [true, 'Book name required']
},
publisher : {
type : String,
required : [true, 'Publisher name required']
},
thumbnail : {
type : String
}
type : {
type : String
},
hasAward : {
type : Boolean
}
});
//method
bookSchema.methods.findByType = function (callback) {
return this.model('Book').find({ type: this.type }, callback);
};
// statics
bookSchema.statics.findBooksWithAward = function (callback) {
Book.find({ hasAward: true }, callback);
};
const Book = mongoose.model('Book', bookSchema);
export default Book;
for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/
Well to me it doesn't mean add anythings by adding Mongoose in front of 'static' or even in front 'instance' keyword.
What I believe meaning and purpose of static is same everywhere, even it's also true for an alien language or some sort of driver which represents Model for building the block like another object-oriented programming. The same also goes for instance.
From Wikipedia:
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of data and behavior. The data and behavior comprise an interface, which specifies how the object may be utilized by any of various consumers[1] of the object.
Data is represented as properties of the object and behaviors are represented as methods of the object. For example, a Window object could have methods such as open and close, while its state (whether it is opened or closed at any given point in time) would be a property.
Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. They are similar to static variables in that sense. An example would be a static method to sum the values of all the variables of every instance of a class. For example, if there were a Product class it might have a static method to compute the average price of all products.
Math.max(double a, double b)
This static method has no owning object and does not run on an instance. It receives all information from its arguments.[7]
A static method can be invoked even if no instances of the class exist yet. Static methods are called "static" because they are resolved at compile time based on the class they are called on and not dynamically as in the case with instance methods, which are resolved polymorphically based on the runtime type of the object.
https://en.wikipedia.org/wiki/Method_(computer_programming)
As everybody said, use methods when we want to operate on a single document, and we use statics when we want to operate on entire collection. But why?
Let's say, we have a schema:
var AnimalSchema = new Schema({
name: String,
type: String
});
now as mentioned in the docs, if you need to check the similar types of a particular document in the db
you can do:
AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
Now, this here refers to the document itself. So, what that means is, this document
doesn't knows which model it belongs to, because methods has nothing to do with the model defaultly, It's only for that particular document obj.
But we can make it work with the model, using this.model('anyModelName').
Now why did we used methods in the case of finding similar types of animals?
For finding similar types of animals we must have an animal obj for which we'll find similar types of.
That animal obj we have let's say:
const Lion = await new Animal({name: Lion, type: "dangerous"});
Next, when we find similar types we need the Lion obj first, we must have it.
So simply, whenever we need the help of a particular obj/document for doing something, We'll use methods.
Now here by chance we also need whole model to search slimier types,
although it is not available directly in methods (remember this.modelName will return undefined). we can get it by setting this.model() to our preferred model, in this case Animal.
That's all for methods.
Now, statics has the whole model at its disposal.
1)Let's say you want to calculate the total price (assume the model has a price field) of all Animals you'll use statics [for that you don't need any particular Animal obj, so we won't use method]
2)You want to find the animals which have yellow skin (assume the model has a skin field), you'll use statics. [ for that we don't need any particular Animal obj, so we won't use method]
eg:
AnimalSchema.statics.findYellowSkin = function findSimilarType (cb) {
return this.find({ skin: "yellow" }, cb);
};
Remember, In methods this refers to the model so, this.modelName will return Animal (in our case).
but just like methods, here also we can (but we don't need to) set the model using.
AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
return this.model('Animal').find({ skin: "yellow" }, cb); //just like in methods
};
so as you can see both of statics and methods are very similar.
Whenever you have a document and you need something to do with that,
use methods. Whenever you need to do something with the whole
model/collection, use statics.
Static methods apply to the entire model on which they are defined whereas instance methods apply only to a specific document within the collection.
this in the context of a static method returns the entire model whereas this in the context of an instance method returns the document.
Lets say for example:
const pokemon = new mongoose.Schema({})
pokemon.statics.getAllWithType = function(type){
// Query the entire model and look for pokemon
// with the same type
// this.find({type : type})
}
pokemon.methods.sayName = function(){
// Say the name of a specific pokemon
// console.log(this.name)
}
const pokemonModel = mongoose.model('schema', pokemon)
const squirtle = new pokemonModel({name : "squirtle"})
// Get all water type pokemon from the model [static method]
pokemonModel.getAllWithType("water")
// Make squirtle say its name [instance method]
squirtle.sayName()
Use .statics for static methods.
Use .methods for instance methods.
//instance method
bookSchema.methods.findByType = function (callback) {
return this.model('Book').find({ type: this.type }, callback);
};
// static method
bookSchema.statics.findBooksWithAward = function (callback) {
Book.find({ hasAward: true }, callback);
};
statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.
statics belongs to the Model and methods belongs to an Instance
I have Students and Classes with a hasMany association between them.
I do this:
myStudent.setClasses(ids). then(function(result) {
console.log(myStudent.Classes);
});
Questions:
What does result parameter mean inside the then-handler?
Why isn't myStudent.Classes up-to-date with the setClasses() change I made?
How can I have Sequelize update the simple Classes member? I need to return a simple JSON response to the caller.
According to docs, result would be the associated Classes (in you case) when sending them to the .setClasses method.
Therefore, your ids param should be in fact the Classes, perhaps you should require them before
Class.findAll({where: {id: ids}})
.on('success', function (classes) {
myStudent.setClasses(classes)
.on('success', function (newAssociations) {
// here now you will have the new classes you introduced into myStudent
// you say you need to return a JSON response, maybe you could send this new associations
})
})
It's not updating because the queries regarding the associations of objects doesn't rely on you original object (myStudent). You should add the new associations (result var, in your example, newAssociations, in mine) in your existing myStudent.Classes array. Maybe reloading your instance should work as well.
Class.findAll({where: {id: ids}})
.on('success', function (classes) {
myStudent.setClasses(classes)
.on('success', function (newAssociations) {
myStudent.Classes = myStudent.Classes || [];
myStudent.Classes.push(newAssociations);
// guessing you're not using that myStudent obj anymore
res.send(myStudent);
})
})
I hope I answered this one with the previous two answers, if not, could you explain what you mean by updating the Classes member?
I'm using mongoosejs and have custom methods to populate some data during pre save. Is there a way to query the db, within methods?
For example:
UserSchema.methods.createRandom = function(callback) {
var random = 123;
this.findOne({random: random}, function(err, doc) {
if (!doc) return callback(random);
this.createRandom(callback);
});
}
UserSchema.pre('save', function(next) {
this.createRandom(function(random) {
this.random = random;
next();
});
}
This is basically what I'm trying to acheive, but this in methods does not reference the model, it references the object to be saved. Anyway to access the model for the findOne().
Thanks!
It's a bit cryptic and I don't know if it's documented anywhere, but I've reliably done this in the past by accessing an instance's model via its constructor property:
this.constructor.findOne({random: random}, function(err, doc) {
I have a read-only API that I'd like Mongoose to always have lean queries for.
Can I enable this either on a schema or connection level to be true by default?
The easiest way is to monkey patch mongoose.Query class to add default lean option:
var __setOptions = mongoose.Query.prototype.setOptions;
mongoose.Query.prototype.setOptions = function(options, overwrite) {
__setOptions.apply(this, arguments);
if (this.options.lean == null) this.options.lean = true;
return this;
};
Mongoose creates new instance of mongoose.Query for every query and setOptions call is a part of mongoose.Query construction.
By patching mongoose.Query class you'll be able to turn lean queries on globally. So you won't need to path all mongoose methods (find, findOne, findById, findOneAndUpdate, etc.).
Mongoose uses Query class for inner calls like populate. It passes original Query options to each sub-query, so there should be no problems, but be careful with this solution anyway.
A hack-around could be performed something like this:
Current way of executing the query:
Model.find().lean().exec(function (err, docs) {
docs[0] instanceof mongoose.Document // false
});
Fiddle with the Model's find method:
var findOriginal = Model.prototype.find;
Model.prototype.find = function() {
return findOriginal.apply(this, arguments).lean();
}
New way of executing the query:
Model.find().exec(function (err, docs) {
docs[0] instanceof mongoose.Document // false
});
I have not tested this code, but if you have tried to override library functionality in JavaScript before, you will easily grasp where I'm getting
I have to use My nestjs Application like this. Its perfectly working for me.
import { Query } from 'mongoose'
Query.prototype.setOptions = function(options: any) {
__setOptions.apply(this, arguments)
if (!this.mongooseOptions().lean) this.mongooseOptions().lean = true
return this
}
Refer to the above comments:
mongoose.Query.prototype.setOptions = function(options, overwrite) {
options = Object.assign({}, options);
if (!options.hasOwnProperty('lean')) {
options.lean = true;
}
__setOptions.call(this, options, overwrite);
return this;
};
If you are worried about the accepted answer by #Leonid Beschastny, the places where you should not use lean, according to Mongoose docs are:
When you modify the query result
You use custom getters or transforms
Source: https://mongoosejs.com/docs/tutorials/lean.html#when-to-use-lean