2016-01-08 31 views
1

我新使用风帆JS。如何在SailsJS中实现beforeDestroy方法?

我有这样

beforeDestroy: function(borrow, next){ 
     return Book.find({id:borrow.product}) 
     .then(function(){ 
      Book.update(borrow.product, {'isBorrowed' : false}) 
     }) 
     .then(function(){ 
      next(); 
     }) 
     .catch(function(error){ 
      next(error); 
     }); 
    } 

方法当我试图破坏数据的书“IsBorrowed”尚真,如何竭力试图删除数据时解决这个问题,首先找到ID其次,更改数据的书IsBorrowed到是假的?谢谢提前

回答

0

下面是一个解决方案(你原来的问题 - 只是切换isBorrowed逻辑四周,你现在需要它):

book.js

module.exports = { 

    schema: true, 
    attributes: { 
    name: {type: 'string', required: true}, 
    desc: {type: 'text'}, 
    isBorrowed: {type: 'boolean', defaultsTo: false} 
    } 

}; 

bookBorrowed.js

module.exports = { 

    schema: true, 

    attributes: { 
    book: {model: 'Book'} 
    }, 

    beforeDestroy: function (criteria, next) { 

    var bookId = criteria.where.id; 
    console.log(bookId); 

    Book.update({id: bookId}, {isBorrowed: true}) 
     .exec(function (err, updatedBook) { 
     if (err) { 
      next('no book..'); 
     } 
     console.log('updated book', updatedBook); 
     next(); 
     }); 
    } 

}; 

你的问题是你应该考虑与id的关系,而不是对象。 另外,传递给beforeDestroy的条件参数有一个where对象,它不是模型。另外,update()函数接受一个对象标准,参见上文。

如果你想测试,用下面的代码片段取代你bootstrap.js:

module.exports.bootstrap = function (cb) { 

    var bk = {name: 'name', desc: 'desc', isBorrowed: false}; 

    Book.create(bk).exec(function (err, book) { 
    if (err) { 
     cb(err); 
    } 
    console.log('book: ', book); 
    var bb = {book: book.id}; 
    BookBorrowed.create(bb).exec(function (err, bkBorrowed) { 
     if (err) { 
     cb(err); 
     } 
     console.log('bkBorrowed: ', bkBorrowed); 
     BookBorrowed.destroy({id: bkBorrowed.id}).exec(function (err, bkBorrowed) { 
     if (err) { 
      cb(err); 
     } 
     cb(); 
     }); 
    }) 
    }); 

}; 
相关问题