使用架构方法在Mongoose For循环中保存项目

时间:2015-02-12 13:25:16

标签: node.js mongodb express mongoose instagram

如果我附加任何额外的验证方法,我在保存正在运行for循环的项目时遇到问题。基本上,我正在构建一个Instagram API应用程序,允许编辑删除不合适的照片。照片从Instagram中分批抽出20张并显示给编辑。如果编辑点击了某张照片,则会先将其放在黑名单上。数据库按ID,然后从主照片数据库中删除。

为了不将列入黑名单的照片重新显示在Feed上,在将项目保存到主照片数据库之前,需要根据黑名单检查照片的Instagram ID。为此,我使用了Schema方法。

现在的问题是,我只能将一张照片保存到数据库中。如果我拿出方法检查,那么我得到所有20个。

这是我的主要创建控制器:

exports.create = function(req, res) {

var topic = req.body.topic || 'nyc';

var path = 'https://api.instagram.com/v1/tags/' + topic + '/media/recent?client_id=' + 'XXXXXXXXXX';


request.get({url: path}, function(err, response){

  if (err){
    console.log('Failed to get data: ', err);
    return res.status(400).json({error: 'Not allowed'});
  }

  else{

    // ------------------------------------------------
    // Make sure we have JSON
    //

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



    // ------------------------------------------------
    // Loop through each response
    //

    for (var i = 0; i < body.data.length; i++ ){
      var photoData = body.data[i];


      // ------------------------------------------------
      // 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);
          })
        }

      });

      // -------------------------------------------------
      //
      // Save
      // 
      // -------------------------------------------------

    } // END FOR LOOP

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

这是我的照片架构:

'use strict';

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var Blacklist = require('../blacklist/blacklist.model');

var PhotoSchema = new Schema({
  created: {type: Date, default: Date.now()},
  date: String,
  link: String,
  username: String,
  profilePicture: String,
  imageThumbnail: {type: String, unique: true},
  imageFullsize: String,
  caption: String,
  userId: String,
  _id: {type: String, unique: true}
});


PhotoSchema.methods.checkBlacklist = function(callback){

  return Blacklist.findById(this._id, callback);

};


module.exports = mongoose.model('Photo', PhotoSchema);

奇怪的是,我在创建控制器中获取了所有20个保存的控制台消息:     console.log(&#39;已保存&#39;,项目);

但实际上只保存了一张照片。有什么想法吗?

由于

2 个答案:

答案 0 :(得分:7)

如果必须对数组中的项执行相同的异步任务,请不要使用常规for循环。查看async.each,它更适合您的方案,例如(仅代码的else部分):

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'} );
});

别忘了安装

npm install async

并要求async

var async = require('async');

答案 1 :(得分:0)

如何递归地解决它

                                saveGames = (depth) => {
                                    if (depth > 0) {
                                        var newGame = new Game({ user: user._id });
                                        newGame.save((err, game) => {
                                            if (err) {
                                                console.log(err);
                                                return res.status(203).json({
                                                    title: 'error',
                                                    error: { message: 'Error Saving Games' }
                                                });
                                            }
                                            user.games.push(game);
                                            user.save((err, user) => {
                                                if (err) {
                                                    console.log(err);
                                                    return res.status(203).json({
                                                        title: 'error',
                                                        error: { message: 'Error Saving Games' }
                                                    });
                                                }
                                                saveGames(depth - 1);
                                            });
                                        });
                                    }
                                }
                                saveGames(5);