gpt4 book ai didi

node.js - 在数组 Mongoose 中搜索对象

转载 作者:太空宇宙 更新时间:2023-11-04 00:29:34 24 4
gpt4 key购买 nike

假设我有一个名为“部门”的模型。我有一个包含房间的数组,每个房间都有一个病人(有一个病人)。

我想获取患者编号等于请求 ID 的患者。有办法实现这一点吗?

var department = mongoose.model('department', {
departmentName: String,
rooms: [
{
roomNumber: String,
width: Number,
height: Number,
posX: Number,
posY: Number,
sanitary: Boolean,
childcareArea: Boolean,
lounge: Boolean,
patient: {
patientnr: Number,
firstname: String,
lastname: String,
reasonOfHospitalization: String,
dateOfHospitalization: Date,
expectedDateOfDischarge: Date,
vegetarian: Boolean,
needsHelp: Boolean,
comments: String,
department: String,
roomNumber: String,
nextTreatment: {
type: String,
shortDescription: String,
timestamp: Date
}
}
}
]
});

//get patient with id
app.get('/api/departments/patients/:id', function(req, res) {
department.find({"patient": {$all :[60022]}}, function (err, patient) {
if (err)
res.send(err)
res.json(patient);
});
});

最佳答案

您可以使用$elemMatch 在您的投影中如下:

//get patient with id
app.get('/api/departments/patients/:id', function(req, res) {
department.findOne(
{ "rooms.patient.patientnr": parseInt(req.params.id) },
{
"rooms": {
"$elemMatch": {
"patient.patientnr": parseInt(req.params.id)
}
}
},
function (err, dept) {
if (err)
res.send(err)
var patient = dept.rooms[0].patient;
res.json(patient);
}
);
});

$ positional operator

//get patient with id
app.get('/api/departments/patients/:id', function(req, res) {
department.findOne(
{ "rooms.patient.patientnr": parseInt(req.params.id) },
{ "rooms.$": 1 },
function (err, dept) {
if (err)
res.send(err)
var patient = dept.rooms[0].patient;
res.json(patient);
}
);
});

或使用聚合框架:

//get patient with id
app.get('/api/departments/patients/:id', function(req, res) {
department.aggregate(
[
{ "$match": { "rooms.patient.patientnr": parseInt(req.params.id) } },
{
"$project": {
"room": {
"$arrayElemAt": [
{
"$filter": {
"input": "$rooms",
"as": "room",
"cond": {
"$eq": [
"$$room.patient.patientnr",
parseInt(req.params.id)
]
}
}
}, 0
]
}
}
}
], function (err, results) {
if (err)
res.send(err)
var patient = results[0].room.patient;
res.json(patient);
}
);
});

关于node.js - 在数组 Mongoose 中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41507689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com