Mongoose: Soporte para virtuales anidados, virtuales en subdocumentos

Creado en 12 feb. 2011  ·  6Comentarios  ·  Fuente: Automattic/mongoose

var Page = new Schema({
    author: {
        first_name: String
      , last_name: String
    }
});
Page.virtual("author.full_name").get(function() {
    return this.author.first_name + " " + this.author.last_name;
});

// Later
myPage = new Page({author: {first_name: "John", last_name: "Doe"}});
myPage.author.full_name; // == undefined
myPage.get("author.full_name"); // == "John Doe"

No he intentado hacer un nuevo esquema para el autor con sus propios virtuales. Tal vez eso funcione, pero de acuerdo con otros informes de problemas, los subesquemas funcionan de manera óptima en arreglos atm, no como subdocumentos simples.

En cuanto a la fuente, esto no parece imposible, solo falta una lógica de división inteligente (".") Al agregar lo virtual al árbol de esquema.

El método get funciona bien por el momento, pero la otra sintaxis sería preferible. :)

Comentario más útil

La solución anterior funciona, pero también deberá activar los virtuales para el esquema anidado:

Variation.set('toJSON', {
    virtuals: true
});

Todos 6 comentarios

Por supuesto, esta corrección también debería aplicarse a métodos en subdocumentos.

¿Qué pasa si el autor es una matriz? ¿Podemos hacer un virtual en cada uno de este arreglo?

+1 soporte para matrices

+100 soporte para matrices

Lo descubrí :.

var Variation = new Schema({
  label: {
    type: String
  }
});

// Virtual must be defined before the subschema is assigned to parent schema
Variation.virtual("name").get(function() {

  // Parent is accessible
  var parent = this.parent();
  return parent.title + ' ' + this.label;
});


var Product = new Schema({
  title: {
    type: String
  }

  variations: {
    type: [Variation]
  }
});

La solución anterior funciona, pero también deberá activar los virtuales para el esquema anidado:

Variation.set('toJSON', {
    virtuals: true
});
¿Fue útil esta página
0 / 5 - 0 calificaciones