0
我有這個功能。不允許接受服務: 僅在可用參數爲真時才被採用。mongodb:只更新文件如果沒有更新
function takeService(req, res) {
var serviceId = req.params.id;
var driverId = req.body.driverId;
Service.findById(serviceId, (err, service) =>{
if (!err) {
if (!service) {
res.status(404).send({message: 'Not found'});
} else {
if (service.available === false) {
res.status(409).send({message: 'The service is taken'});
} else {
Service.findByIdAndUpdate(serviceId, {
driverId,
status: 1,
available: false
}, (err, serviceUpdated) =>{
if (!err && serviceUpdated) {
res.status(200).send({message: "tomado"});
}
});
}
}
}
});
}
架構:
var ServiceSchema = Schema({
clientId: {
type: String,
ref: 'Client'
},
available: Boolean,
routeId: {
type: String,
ref: 'Route'
},
date: Date,
radius: Number,
driverId: {
type: String,
ref: 'Driver'
},
status: Number,
time: String,
createdTime: Number,
rateId: {
type: String,
ref: 'Rate'
}
});
var DriverSchema = Schema({
name: String,
surname: String,
username: String,
password: String,
status: { type: Number, default: 0 },
oneSignalId: String,
plate: String,
make: String,
year: String,
model: String,
groupId: [{
type: String,
ref: 'DriverGroup'
}],
unit: String,
telephone: String
});
問題是當兩個設備調用這個函數,在某些情況下都找到該文件,並檢查是否可用,然後更新都在同一個文檔。我正在爲自動檢查此屬性的架構中尋找一些驗證。
你可以改變'findByIdAndUpdate',或使一個新的'findAvailableByIdAndUpdate'包括' 「可用」:TRUE'在蒙戈查詢。如果它沒有更新任何文件,其他的東西就會贏得比賽。 – Joe