Multi Relationships with Mongoose

0

is the first time I write, I have always solved the problems with questions from others, but this time I have not found a solution for this:

I have a Schema where I have several references to other Schemas:

var mongoose = require('mongoose');
require('mongoose-double')(mongoose);
var Schema   = mongoose.Schema;
var User     = mongoose.model('User');
var Persona  = mongoose.model('Persona');
var PtoVenta = mongoose.model('PuntoVenta');
var FrmaPago = mongoose.model('FormaPago');
var Item     = mongoose.model('Item');

var SchemaTypes = mongoose.Schema.Types;

// Factura Schema
var FacturaSchema   = new Schema({
    tipo_doc: {type: String, enum: ['Factura', 'Recibo'], required: true},
    pto_venta: { type: mongoose.Schema.Types.ObjectId, ref: 'PtoVenta'},
    nro_factura: Number,
    fecha: { type: Date, default: Date.now },
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    cabecera: {
        persona: { type: mongoose.Schema.Types.ObjectId, ref: 'Persona'},
        apellido: String,
        nombre: String,
        empresa: String,
        CUIT: String,
        direccion: {
            calle: String,
            localidad: String,
            provincia: String,
            pais: String,
            cod_postal: String
        },
    },
    total: SchemaTypes.Double,
    subtotal: SchemaTypes.Double,
    impuesto: SchemaTypes.Double,
    observaciones: String,
    transaccion: {
        forma_pago: { type: mongoose.Schema.Types.ObjectId, ref: 'FormaPago'},
        detalle: String
    },
    items: [
        {
            item: { type: Schema.ObjectId, ref: "FacturaDetalle" }
        }
    ]
    status: String
});

I need to perform the populate of each reference, but I can not figure out how to do it.

Factura.find(query, function(err, result) {
    if (err) res.send(err);
    res.json(result);
});

I thank you for helping me to make all the populates or to guide me as I do it!

    
asked by Ezequiel Cohort 23.01.2017 в 18:21
source

1 answer

1

Depending on the mongoose version you are using, it can be:

Factura.find(query)
.populate('PtoVenta User Persona FormaPago FacturaDetalle')
.exec(function(err, result) {
    if (err) res.send(err);
    res.json(result); 
});

Or:

Factura.find(query)
.populate('PtoVenta').populate('User')
.populate('Persona').populate('FormaPago').populate('FacturaDetalle')
.exec(function(err, result) {
    if (err) res.send(err);
    res.json(result); 
});
    
answered by 23.01.2017 / 19:34
source