Q
Q
quex2014-02-17 17:02:33
Node.js
quex, 2014-02-17 17:02:33

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.

The method is used at the document level (captain obvious), the document has an isNew attribute (by the way, calling init sets it to false), the init event can be handled through middleware.
Thus, as far as I understand, when creating a document (model instance), an existence check should occur such a document in the collection, and if the result is positive, the document is initialized.
preliminarily add a document to the collection, {_id:1, title: "item123"}
then execute
...
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});

after execution, the console is empty, .init() was not called, so the init event was not emitted. those. no initialization occurs when the document is created. why? Explain in general the principle of operation of this mechanism. or the mongoose just provides functionality, and the developer decides when and where to use .init() in his methods. But then why does the Mongoose#Model() model constructor have a last parameter, skipInit (which is false by default), which suggests that this mechanism has already been implemented.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Q
quex, 2014-02-17
@quex

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 question

Ask a Question

731 491 924 answers to any question