保存项目在Mongoose For Loop与模式方法 [英] Saving Items In Mongoose For Loop With Schema Methods

查看:100
本文介绍了保存项目在Mongoose For Loop与模式方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我附加任何额外的验证方法,我有一个问题,保存项目运行for循环。基本上,我正在建立一个instagram API应用程序,允许编辑器删除不方便的照片。照片从Instagram分批从20提取并显示给编辑。如果编辑点击一张照片,首先将它放在黑名单的数据库中,然后从主照片数据库中删除。



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



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



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

  exports.create = function(req,res){

var topic = req.body.topic || NYC;

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


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

if(err){
console.log '



$ b其他{

// ---------------------------------------- --------
//确保我们有JSON
//

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



// ------------------------------------- -----------
//循环遍历每个响应
//

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


// ------------------ ------------------------------
//如果没有标题,跳过它
//

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

// --------------------------------------- ---------
//创建新的照片对象
//

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

});

// ---------------------------------------- ---------
//
//保存
//
// ---------------- ---------------------------------

} // END FOR LOOP

console.log('照片已保存');
return res.json(201,{msg:'照片更新'});
}
});
};

这是我的照片模式:

 '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',item);



但实际上只保存了一张照片。任何想法为什么?



谢谢

解决方案

当你必须执行对于数组中的项目,同一异步任务不要使用常规for循环。查看 async.each ,它更适合您的场景,就像($ code> else 部分代码):

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

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

// ----------------- -------------------------------
//如果没有标题,跳过
/ /

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

// -------------------------------------- ----------
//创建新的照片对象
//

var photo = new Photo({
link:photoData.link ,
用户名: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){
如果(err){
console.log(err);
}

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

});

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

console.log('照片保存');
return res.json(201,{msg:'照片更新'});
});

不要忘记安装

  npm install async 

,需要 async

  var async = require('async'); 


I'm having a problem saving items running through for loop if I attach any extra validation methods. Basically, I'm building an instagram API app that allows editors to remove photos that are unseemly. Photos are pulled from Instagram in batches of 20 and displayed to editors. If an editor clicks a photo, it is first put on a 'blacklist' database by ID, then deleted from the main photo database.

In order to not have blacklisted photos reappear on the feed, before saving an item to the main photo database, it needs to check the Instagram ID of the photo against the blacklist. To do this, I'm using a Schema method.

The problem right now, is that I'm only getting ONE photo saved to the DB. If I take out the method check, then I get all 20.

Here's my main create controller:

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

And here's my Schema for photos:

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

Strangely, I'm getting console messages for all 20 saves in the create controller: console.log('Saved', item);

But only ONE photo is actually saved. Any ideas why?

Thanks

解决方案

When you have to perform the same asynchronous task for items in an array, don't use a regular for loop. Check out async.each, it fits better in your scenario, like (just the else part of your code):

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

Don't forget to install

npm install async

and require async:

var async = require('async');

这篇关于保存项目在Mongoose For Loop与模式方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆