【发布时间】:2021-08-31 17:22:34
【问题描述】:
我正在尝试在 mongoDB 中实现插槽预订系统。 我想将一个字符串,它是一个 userId(来自用户集合的 ObjectId)推送到一个名为 userId 的数组中,该数组位于 slotsAvailable 中的许多类似对象之一中数组。
问题是,我无法从 slotAvailable 数组中定位特定插槽。我也尝试过索引,因为 slotAvailable 是一个数组。
我想选择一个特定的日子(比如 day:1),我想从“slotsAvailable”对象中通过它的 ID 选择一个特定的插槽(比如 id:5)。之后,我想将 ObjectId 推送到 userId 数组中,将 count 增加到 9,当计数达到 9 时,我想更新 isAvailable 到 假。
我应该运行什么查询来达到同样的效果?
我执行了以下查询:
db.vaccines.findOne({day:1})
它返回:
{
"_id" : ObjectId("60c8b8cf7bd10f9d7876f3b1"),
"totalBooking" : 0,
"day" : 1,
"slotsAvailable" : [
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 0
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 1
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 2
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 3
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 4
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 5
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 6
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 7
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 8
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 9
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 10
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 11
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 12
},
{
"userId" : [ ],
"count" : 0,
"isAvailable" : true,
"id" : 13
}
]
}
我的nodeJs代码是:
async function bookVaccineSlot(args){
const {userId} = args
// get vaccine collection from DB
const vaccines = mongoose.connection.collection('vaccines');
// call getSlotId routine to get the value of slot number using slotTime( slot start time in 24-hour format)
const {day,slotTime} = args;
const slotID = getSlotId(slotTime);
if(1<=slotID && slotID<=14){
let index = slotID - 1;
let query = {day:day,"slotsAvailable.id":index};
let updatedDocument = {
$push:{
"slotsAvailable.$.userId":userId,
},
$set: {
"slotsAvailable.$.": 'slotsAvailable.count'+1
}
}
// get slot of particular day from the 'vaccines' collection, fetched above
const vaccinationDay = await vaccines.updateOne(query,updatedDocument)
return vaccinationDay;
}
}
【问题讨论】:
-
以上链接是在 mongo shell 和 NodeJS 中的 MongoDB 驱动程序中输入相同查询后发生的详细 sn-p