Answer the question
In order to leave comments, you need to log in
Example of using Document#init in mongoose
I just can't figure out how to eat it. There is no clear information about this in the documentation (there is no mention of the method itself in the API documentation at all)
From the comment to this method in the sorts:
// Called internally after a document is returned from mongodb.
{_id:1, title: "item123"}
...
var schema = {_id: Number, title: String};
var itemSchema = mongoose.Schema(schema, {versionKey: false});
var itemModel = mongoose.model('items',itemSchema);
// попробуем вывести документ в консоль после инициализации
itemSchema.post('init', function(doc){
console.log('post init function called');
console.log(doc);
});
var item = new itemModel({_id:1});
Answer the question
In order to leave comments, you need to log in
after in-depth study and experimentation, the answer was found. when a document is created by a construct var item = itemsModel({..})
, no initialization occurs, the document is a priori considered new. the .init() method is called on query results (documents) when calling Model.find, Model.findById, etc.
Thus, all this nonsense with initialization, attributes isNew, isInit, etc. can be useful, for example, in callbacks, when the same callback can be applied both to the results of the selection and to the created documents through the constructor.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question