我在說迴環推送組件。我試圖攔截「安裝」模型的「創建」方法。我的代碼看起來是這樣的 -迴環奇怪行爲
服務器的/ boot/installationex.js
module.exports = function (app) {
var Installation = app.models.Installation;
var create = Installation.create;
Installation.create = function (data, cb) {
//reinitializing old implementation
this.create = create;
console.log("Received data: "+JSON.stringify(data));
if (!data || !data.imei) {
console.log("No data or imei was provided, creating new");
this.create(data, cb);
return;
}
//saving 'this' reference
var that = this;
//search by imei filter
var filter = {where: {imei: data.imei}};
this.findOne(filter, function (err, result) {
if (err) {
console.log("Error occurred while looking for installation by IMEI");
cb(err);
return;
}
if (!result) {
console.log("No installation found by IMEI, will create a new installation");
that.create(data, cb);
return;
}
console.log("Found existing installation with id: " + JSON.stringify(result));
result.deviceToken = result.gpsLocation = result.osVersion = result.vendor = result.phoneNumbers = null;
if (data.deviceToken) {
result.deviceToken = data.deviceToken;
}
if (data.gpsLocation) {
result.gpsLocation = data.gpsLocation;
}
if (data.osVersion) {
result.osVersion = data.osVersion;
}
if (data.vendor) {
//result.vendor=data.vendor;
result.vendor = 'jahid';
}
if (data.phoneNumbers) {
result.phoneNumbers = data.phoneNumbers;
}
that.upsert(result, cb);
});
}
}
遺憾的是這段代碼被調用一次,我指的是第一次。之後,這段代碼從不被調用。我通過查看日誌來確定。它只是第一次打印日誌。之後它不打印任何日誌。
任何想法爲什麼這個膠水代碼只被調用一次?我的意圖是攔截安裝模型的所有創建方法調用。並檢查是否已有提供「IMEI」的條目,如果是,則重新使用該條目。否則,創建新的。
在此先感謝。
最好的問候,
Jahid
任何例子,我怎麼能叫「findOrCreate()」?我的意思不是服務器端,但我需要客戶端代碼。 – 2014-11-23 10:01:07