找到每个doc的执行方法

时间:2014-12-24 19:44:27

标签: node.js express mongoose

我想在发送json数据之前执行isAparticipant方法,我不知道正确的方法,而event.find()返回一个json而不是模型的实例,我想如果我做一个forEach on evts(JSON数据)这是一个坏主意。

控制器:

var Event = require('../../model/event');
var eventsController = {

      // Get Events List 
      index: function(req, res){
        // var currentUser = req.user;
         Event.find(function(err, evts){
           if(err){
            res.status(400).json({success: false, errors: err.errors});
           }else{
            res.status(200).json({success: true, events: evts});
           }
         });
      }

 };

 // Export eventsController
 module.exports = eventsController;

型号:

var mongoose = require('mongoose');
var EventsSchema = new mongoose.Schema({

     title:{
      type: String,
      unique: true,
      required: true,
     },

    teaser: {
      type: String,
      required: true
    },

    description: {
      type: String,
      required: true
    },

    participants: [{type: mongoose.Schema.Types.ObjectId, ref: 'User'}],

    start_date: {
      type: Date,
      required: true
    },

    end_date: {
      type: Date,
      required: true
    },

    lat: {
      type: String,
      required: true
    },

    lng: {
      type: String,
      required: true
    },

    created_at: {
      type: Date,
      default: Date.now
    },

    updated_at: {
      type: Date,
      default: Date.now
    }

});



// Check If User is A particpant
EventsSchema.methods.isAparticipant = function(userId) {
  if(this.participants.indexOf(mongoose.Schema.Types.ObjectId(userId)) != -1){
     this.isParticipant = true;
  }else{
     this.isParticipant = false;
  }
};



var Evt = mongoose.model('Event', EventsSchema);



module.exports = Evt;

1 个答案:

答案 0 :(得分:1)

由于evts是一个数组,您可以执行forEach函数以同步方式遍历数组:

evts.forEach(function(evt) {
    evt.isParticipant(req.user.id);
});
res.status(200).json({success: true, events: evts});