如果我附加任何额外的验证方法,我在保存通过 for 循环运行的项目时遇到问题。基本上,我正在构建一个 Instagram API 应用程序,允许编辑者删除不雅的照片。照片会以 20 张为一组从 Instagram 中提取并展示给编辑。如果编辑者点击一张照片,它首先会根据 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('已保存', 项目);
但实际上只保存了一张照片。有什么想法吗?
Thanks