Mongoose toObject: {virtuals: true}

I am trying to learn MongoDB / Node, and I noticed that in the circuit I often see something like this:

toObject: { virtuals: true } toJSON: { virtuals: true } 

What do these two lines mean?

+5
source share
1 answer

This is not "MongoDB", but ODM-specific Mongoose.

Mongoose has the concept of "virtual" fields in a schema definition. This essentially allows this (egregious glean from the documentation):

 var personSchema = new Schema({ name: { first: String, last: String } }); var Person = mongoose.model( "Person", personSchema ); 

But suppose you just want to “save” these properties, but then you have something that you can get in code called “fullname”. Here the "virtual" includes:

 personSchema.virtual("name.full").get(function () { return this.name.first + ' ' + this.name.last; }); 

Now we can do something like this:

 var bad = new Person({ name: { "first": "Walter", "last": "White" } }); console.log("%s is insane", bad.name.full); // Walter White is insane 

So name.full doesn't actually exist in the data, it's just a representation of the schema in the code. But, of course, it is tied to a function that uses the actual data present in the object to create a method that returns a value that combines the two fields for the code in the method.

This is basically what the "virtual" fields are. They are actually “methods” defined in the “object” document that represent a value that is not “stored” or stored in the database. Usually they are based on the actual stored values ​​from the data store.

But really clarify your direct question. Mongoose only "serializes" the contents of the internal structure of the object based on the "saved" fields by default. So what these two lines mean:

  • toObject () . This creates a “simple” or “raw” representation of the object’s data without all the other parts of the mongoose magic of the extended object. But the purpose of the "virtual" ones is to return these methods to the part of the returned object. Basically just a simple object called:

      var model = Model.new({ "name": { "first": "Walter", "last": "White" }); console.log( model.toObject() ); 
  • toJSON () . You can call this method explicitly and as shown above, but the most common use comes from the JSON parser, as shown below, where it is implicitly called. The same principles apply as stated above. "Virtual" includes the result of these methods in a serialized release, for example:

      var model = Model.new({ "name": { "first": "Walter", "last": "White" }); JSON.stringify( model, undefined, 2 ); 

So, in the second case, there is an “implicit” call to the .toJSON() method of the object. What the configuration does says that this method not only includes the data or “fields” present in the object, but also certain “virtual” methods and the result they produce. Same for .toObject() .

+8
source

Source: https://habr.com/ru/post/1206801/


All Articles