Saturday 20 May 2017

Populate and Virtuals with mongoose returning imcomplete data

I need some help with populate and virtuals with mongoose.

When I get a list of the "cidade" using

router.get('/',function(req,res,next){ ....

I´d like to populate the result with some additional info from "estado" as "_id " and "nome".

Buit, when I print the results in the console, I have only results from "cidade" and no data informations from "estado".

What am I doing wrong?

//collections data sample

//cidades

    "_id":213123......
    "uf":"AL"
    "cidade":"ARARAS"
......

//estados

    "_id":2aaa3123......
    "uf":"AL"
    "nome":"AZALU"
.....

//router to cidades

'use strict';
const express = require('express');
const router = express.Router();
//const querystring = require('querystring');
const Cidade = require('../models/cidade'); 
const callback=function(err,data,res){
     console.log(data);//??? only data from "cidade", no "estado" info
     if (err) return res.status(500).json(err);
     return res.status(200).send(data);
};

router.get('/',function(req,res,next){
    const query=new RegExp(req.query.where,'i');
    Cidade.find({ cidade: query })
    .populate('id_estado')
    .exec( (err,data) => {
       callback(err,data,res)
    })
});

//model estados

estadosSchema = new mongoose.Schema({
  uf: {type: String, unique:true},
  nome: {type: String, unique:true}
});
module.exports = mongoose.model('Estado', estadosSchema,'estados' );

//model cidades

cidadesSchema = new mongoose.Schema({
  uf: {type: String, unique:true},
  cidade: {type: String, unique:true}
},{ toJSON: { virtuals: true } });

cidadesSchema.virtual('id_estado', {
  ref: 'Estado', // The model to use
  localField: 'uf', // Find Estado where `localField`
  foreignField: 'uf', // is equal to `foreignField`
  justOne: false
});


module.exports = mongoose.model('Cidade', cidadesSchema,'cidades' );



via Luiz Alves

No comments:

Post a Comment