2017-05-05 51 views
0

我剛剛開始使用貓鼬查詢方法,他們真的很酷。我做了一個查詢方法來了解對象的所有權。如果是,那麼它是他自己的,那麼對象的值將被顯示,否則它應該執行一個錯誤,如返回一些錯誤,而不是別的。如何在貓鼬查詢方法中返回錯誤?

someSchema.query.isOwner = function(user) { 
    if (user.admin) 
     return this; 
    /* I know this will not work please suggesta solution for this too */ 
    else if (user._id === iShouldbeAbleToAccessTheObjectHere._id) 
     return this; 
    else 
     // Put this into the error of exec 
     return new Error('Permission denied!'); 
}; 

// This is how I'll use it 
SomeModel 
    .findById(someId) 
    .isOwner(currentUser) 
    .exec((err, result) => { 
     if (err) 
     res.json({ error : err }); 
     res.json({ data : result }); 
    }); 

回答

1
//model.js 
var ObjectId = require('mongoose').Types.ObjectId; 
var someModel = new mongoose.model('somemodel',someSchema); 

someModel.findByIdAndCheckOwnership = function(id, callback){ 

    this.find({ _id : new ObjectId(id), admin : true}, function(err, user){ 
     if(err){ 
      callback('Your Custom Error Msg', null); 
     } 
     else{ 
      callback(null, user); 
     } 
    }); 
} 

//use of model in some other.js 
SomeModel.findByIdAndCheckOwnership(id, function(err, user){ 

    if(err){ 
     res.json({ error :err }); 
    } 
    else{ 
     res.json({ user : user }); 
    } 
}); 

//populate 
someModel.findByIdAndCheckOwnership = function(id, callback){ 

    this.find({ _id : new ObjectId(id), admin : true}).populate('your_population_fields').exec(function(err, user){ 
     if(err){ 
      callback('Your Custom Error Msg', null); 
     } 
     else{ 
      callback(null, user); 
     } 
    }); 
} 
+0

有什麼辦法,我可以設置回調的錯誤? –

+0

@Johnfoo我已經更新了答案。請檢查:) –

+0

簡單易行,非常感謝您的幫助! –