NodeJS / MongoDB – 匹配数组中值与login用户的值

我希望用户只能报告一次文件/video。 通过将用户标识推送到数组,然后检查用户是否已经报告了该文件。 到目前为止,我能够find当前用户,然后VideoID,加1,然后将其推送到reportedBy数组。 但是,当我们检查当前用户是否已经报告过这个文件的时候,我感到非常遗憾。 任何提示/帮助将不胜感激! 🙂

我的路线

router.get('/report/:videoLink', function(req, res, next){ async.waterfall([ function(callback){ User.findOne({_id: req.user._id}, function(err, foundUser){ if(err) return next(err) callback(err, foundUser) }) }, function(foundUser, callback){ Video.findOne({videoLink: req.params.videoLink}, function(err, reportVideo){ reportVideo.reports++; reportVideo.reportedBy.push(foundUser); if (reportVideo.reports > 4) { reportVideo.remove(); } reportVideo.save(function(err){ if(err) return next(); }); res.redirect('/'); }); } ]); }); 

我的模式

  var mongoose = require('mongoose'); var Schema = mongoose.Schema; var random = require('mongoose-simple-random'); var fragSchema = new Schema({ title: String, videoLink: {type: String, unique: true, required: true}, category: String, upVotes: {type: Number, default: 0}, downVotes: {type: Number, default: 0}, voted: {type: Boolean, default: false}, reports: {type: Number, default: 0}, reportedBy: [{ type: Schema.Types.ObjectId, ref: 'User'}], ownByUser: {type: Schema.Types.ObjectId, ref: 'User'}, date: { type: Date, default: Date.now } }); fragSchema.plugin(random); module.exports = mongoose.model('Frag', fragSchema); 

       

网上收集的解决方案 "NodeJS / MongoDB – 匹配数组中值与login用户的值"

只有在该用户报告之前,才能find该video:

 Video.findOne({ videoLink: req.params.videoLink, reportedBy: foundUser._id, }, ... 

只有在以前没有报告的情况下,才能findvideo:

 Video.findOne({ videoLink: req.params.videoLink, reportedBy: {$nin: [foundUser._id]}, }, ... 

有很多方法可以实现,但你明白了。

如果你想findvideo,然后testing是否已经由该用户报告,那么你的Video.findOnecallback里面有这样的Video.findOne

 if (reportVideo.reportedBy.indexOf(foundUser._id) < 0) { // not reported by that user yet } else { // already reported by that user } 

如果你使用lodash那么你可以使用:

 if (_.includes(reportVideo.reportedBy, foundUser._id)) { // already reported by that user } else { // not reported by that user yet } 

确保你的ID是string,也许你需要在比较之前使用.toString()或类似的东西。