How to query and update document by using single query?
I have documents likes the following:
{
"_id": "538584aad48c6cdc3f07a2b3",
"startTime": "2014-06-12T21:30:00.000Z",
"endTime": "2014-06-12T22:00:00.000Z",
},
{
"_id": "538584b1d48c6cdc3f07a2b4",
"startTime": "2014-06-12T22:30:00.000Z",
"endTime": "2014-06-12T23:00:00.000Z",
}
As you can see the documents above have startTime and endTime. I need to update some document that don't overlap others. I can make things to work by using two queries:
var event_id = "538584b1d48c6cdc3f07a2b4";
var event = {
startTime: "2014-06-12T21:30:00.000Z"
endTime: "2014-06-12T23:30:00.000Z"
};
Model.count({
_id: {$ne: event_id },
"$or": [
{"$and": [
{"startTime":{"$lte":event.startTime},"endTime":{"$gt":event.startTime}},
{"startTime":{"$lte":event.endTime},"endTime":{"$lt":event.endTime}}
]},
{"$and":[
{"startTime":{"$lte":event.startTime},"endTime":{"$gte":event.startTime}},
{"startTime":{"$lte":event.endTime},"endTime":{"$gte":event.endTime}}
]}
]
}, function (err, count) {
if (err) return next(err);
if (count) {
return next(new Error('Event overlapping'));
}
return Model.findOneAndUpdate({_id: event_id}, event, function (err, event) {
if (err) return next(err);
return res.json(200, event);
});
});
As you can see from the code above I do first query for checking of existing event that could overlaps. And then I do update.
Is it possible to make updating by using single query?
链接地址: http://www.djcxy.com/p/61950.html下一篇: 如何使用单个查询来查询和更新文档?