我收到來自Mongoose FindOne的空響應,如果我把參數作爲dateString參數。我使用nodejs和貓鼬。貓鼬FindOne不工作
這裏是我的代碼:
var Service = app.models.service;
controller.newService = function(req, res) {
var date = new Date();
var dateString = date.toString();
var countHours = 1;
var user = req.decoded;
var findProfessional = function(){
console.log(countHours);
console.log(user._doc._id);
console.log(req.body.service[0].tipo);
console.log(dateString);
Service.findOne({
tipo: req.body.service[0].tipo,
client: user._doc._id,
dateOpen: dateString
}, function(err, service) {
console.log(service);
if (err) throw err;
if (!service) {
console.log("service not found");
} else if (service) {
if (service.status == 'open' && countHours <= 24) {
setTimeout(function(){
Professional.find({
'services.name': req.body.service[0].tipo
}, function(err, professional) {
if (err) throw err;
if (professional) {
DO STUFF
} else {
DO STUFF
res.json({ success: false, message: 'No professionals found' });
};
});
countHours++;
findProfessional();
}, 10000);
} else if (service.status != 'open'){
// DO STUFF
} else if (countHours > 24){
//DO STUFF
}
}
});
};
這裏是我的架構:
var schemaServices = mongoose.Schema({
tipo: {
type: String,
required: true
},
client: {
type: String,
required: true
},
dateOpen: {
type: String,
required: true
},
dateClose: {
type: String,
},
professional: {
type: String
},
status: {
type: String,
required: true
},
services: {
type: [{name: String,
preco: String,
tipo: String,
tipoCusto: String,
pedido: String}],
required: true
},
visitDay: {
type: String
},
visitHour: {
type: String
},
address: {
type: [{cep: String,
street: String,
number: String,
comp: String,
district: String,
city: String}],
required: true
}
});
schemaServices.index({client: 1, tipo: 1, dateOpen: 1}, {unique: true});
什麼我的代碼嗎?
當對該路由發出請求時,節點保存新服務並尋找專業人員完成這項工作。它一直在尋找,直到定時器計數小時達到24或有一個專業的工作。服務器正在保存服務沒有問題,但我需要檢查剛剛保存的服務的狀態,並且當我將dateOpen:dateString放入時,我正面臨Service.findOne()返回空值的問題。
問題是
Service.findOne({
tipo: req.body.service[0].tipo,
client: user._doc._id,
dateOpen: dateString
}
總是返回般的服務一個空值不存在。但是如果我在使用mongo的提示中進行了相同的查詢,我得到了正確的服務。
我做了一些測試,並觀察到了一些東西:
- 該console.logs打印好了它應該打印。從參數dateString在Service.findOne()它的工作原理
所以,我認爲,誤差與dateString有關,但我看不出它是什麼:
- 當我刪除dateOpen。
希望有人能幫助我,
謝謝你提前!
您正在將日期保存爲字符串。檢查它們的格式是否相同。否則,它不會返回所需的結果。 我建議將日期保存爲日期類型。然後,您可以直接在查詢中使用Date()對象來查找結果。 – Sohel
是的,看你的文件,以及你的console.log(dateString)的結果。隨意在你的問題中發佈一個例子。 – dyouberg
謝謝你們,剛解決。格式是一樣的。 –