Friday, 2 June 2017

Copying between collections with mongoose

I need import some data from a collection to other.

Hi, I need to import from source collection 'Tuss_22' to target collection 'Convenio' filling 'Convenio.procedimentos' array.

I am trying clear the array 'Convenio.procedimentos' before insert a new by a 'forEach' in Tuss_22.

But I am get an error of 'exec is not a function'.

///Schemas and router

const express = require('express');
const router = express.Router();
const Convenio = require('../models/convenio');
const Tuss_22 = require('../models/tuss_22');


var conveniosSchema = new mongoose.Schema({
  nr: {type: Number, unique:true},
  procedimentos:[{codigo:{type:String},descricao:{type:String},tipo:{type:mongoose.Schema.Types, ref:'TipoConsulta'}}]
});

//router

    router.importarTabelaTUSS=function(req,res,next){   
        console.log(req);
        const query={};
        Convenio.findById(req.params.id, function (err, data) {  
            // Handle any possible database errors
            if (err) {
                res.status(500).send(err);
                return next(error);
            } else {
                // Drop entire other collection
                data.procedimentos.remove().exec( (err_p,data_p) => {
                    Tuss_22.find({}, (err_t,data_t) => { 
                       data_t.forEach(function(doc){
                        data.procedimentos.push({'codigo':doc.codigo, 'descricao':doc.descricao}); // start to replace
                       });
                    });
                })
            }
        })
    };



via Luiz Alves

No comments:

Post a Comment