使用模式方法在 Mongoose For 循环中保存项目

Saving Items In Mongoose For Loop With Schema Methods

如果我附加任何额外的验证方法,我在通过 for 循环保存项目 运行 时遇到问题。基本上,我正在构建一个 instagram API 应用程序,允许编辑删除不合时宜的照片。照片以 20 张为一组从 Instagram 中提取并显示给编辑。如果编辑点击一张照片,它首先会按 ID 放入 'blacklist' 数据库,然后从主照片数据库中删除。

为了不让列入黑名单的照片再次出现在 Feed 上,在将项目保存到主照片数据库之前,需要根据黑名单检查照片的 Instagram ID。为此,我使用了架构方法。

现在的问题是,我只将一张照片保存到数据库中。如果我取出方法检查,那么我得到所有 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('Saved', 项);

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

谢谢

当您必须对数组中的项目执行相同的异步任务时,请不要使用常规的 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');

递归求解如何

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