sql >> Base de Datos >  >> NoSQL >> MongoDB

Guardar elementos en Mongoose For Loop con métodos de esquema

Cuando tenga que realizar la misma tarea asíncrona para los elementos de una matriz, no utilice un bucle for normal. Consulte async.each , encaja mejor en su escenario, como (solo el else parte de su código):

var body = JSON.parse(response.body);

async.each(body.data, function (photoData, callback) {

  // ------------------------------------------------
  // If there is no caption, skip it
  //

  if (!photoData.caption){
    text = '';
  }
  else{
    text = photoData.caption;
  }

  // ------------------------------------------------
  // Create new photo object
  //

  var photo = new Photo({
    link: photoData.link,
    username: photoData.user.username,
    profilePicture: photoData.user.profile_picture,
    imageThumbnail: photoData.images.thumbnail.url,
    imageFullsize: photoData.images.standard_resolution.url,
    caption: text,
    userId: photoData.user.id,
    date: photoData.created_time,
    _id: photoData.id
  });

  photo.checkBlacklist(function(err, blacklist){

    if (!blacklist){
      photo.save(function(err, item){
        if (err){
          console.log(err);
        }

        console.log('Saved', item);
        callback();
      });
    }

  });

}, function (error) {
  if (error) res.json(500, {error: error});

  console.log('Photos saved');
  return res.json(201, {msg: 'Photos updated'} );
});

No olvides instalar

npm install async

y requieren async :

var async = require('async');