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