Node.js 如何在SailsJS中实现预销毁方法?
我刚开始使用sails JS 我有这样的方法Node.js 如何在SailsJS中实现预销毁方法?,node.js,sails.js,Node.js,Sails.js,我刚开始使用sails JS 我有这样的方法 beforeDestroy: function(borrow, next){ return Book.find({id:borrow.product}) .then(function(){ Book.update(borrow.product, {'isBorrowed' : false}) }) .then(function(){ n
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);
});
}
当我试图销毁数据簿“IsFrood”时仍然为真,当我试图删除数据时,如何解决这个问题,首先查找id,然后将数据簿IsFrood更改为假?感谢Advance这里有一个解决方案(针对您最初的问题-只需根据您现在的需要切换ISBorrow逻辑):
book.js
module.exports = {
schema: true,
attributes: {
name: {type: 'string', required: true},
desc: {type: 'text'},
isBorrowed: {type: 'boolean', defaultsTo: false}
}
};
bookbrowed.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的criteria参数有一个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();
});
})
});
};
以下是一个解决方案(针对您最初的问题-只需在您现在需要时切换ISBorrow逻辑):
book.js
module.exports = {
schema: true,
attributes: {
name: {type: 'string', required: true},
desc: {type: 'text'},
isBorrowed: {type: 'boolean', defaultsTo: false}
}
};
bookbrowed.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的criteria参数有一个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();
});
})
});
};