gpt4 book ai didi

node.js - 如何使用 mongoose 和 Node.js 只检索 Azure Cosmos 中的子对象?

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:31 26 4
gpt4 key购买 nike

我正在将 Azure cosmos db 与 Mongodb API 结合使用。我还使用 mongoose 创建模式并在数据库中创建新文档。我也在使用 Node.js。

此时,我正在考虑对嵌入文档使用一对多关系。

数据结构是这样的:

{
"_id" : "locality1",
"_type" : "Locality",
"name" : "Wallmart",
"subsectionList" : [
{
"_id" : "subsection1",
"_type" : "SubSection",
"name" : "First floor",
"sensorList" : [
{
"_id" : "sensor1",
"_type" : "Sensor",
"placement" : "In the hallway"
},
{
"_id" : "sensor2",
"_type" : "Sensor",
"placement" : "In the ceiling"
}
]
},
{
"_id" : "subsection2",
"_type" : "SubSection",
"name" : "Second floor",
"sensorList" : [ ],
}
],
}

我只想检索“sensor1”对象,而不是来自父对象的任何内容。

使用查询,我只能检索整个“locality1”对象,及其所有底层子部分和传感器。从更大的范围来看,这是不必要的大量数据。

这是我到目前为止的查询。

Locality.find().where('subsectionList.sensorList._id').equals("sensor1").then(doc => {
console.log(doc)
})

我很感激任何提示! :)

最佳答案

根据我的测试,即使我遵循提到的参数 here ,我也无法摆脱 _id 属性。 。

Locality.find({},'subsectionList', function (err, locas) 

上面的查询仍然返回包含_id属性的结果。(似乎是默认项)

我从这个 blog 得到了一个解决方法您可以循环数组来过滤所需的列。

var mongoose = require('mongoose');
var COSMOSDB_CONNSTR= "mongodb://***.documents.azure.com:10255/db";
var COSMODDB_USER= "***";
var COSMOSDB_PASSWORD= "***";

mongoose.connect(COSMOSDB_CONNSTR+"?ssl=true&replicaSet=globaldb", {
auth: {
user: COSMODDB_USER,
password: COSMOSDB_PASSWORD
}
}).then(() => console.log('Connection to CosmosDB successful'))
.catch((err) => console.error(err));

const Locality = mongoose.model('Locality', new mongoose.Schema({
_id: String,
subsectionList: [{
sensorList: [{
_id: String,
_type: String,
placement: String
}]
}]
}));

Locality.find({},'subsectionList', function (err, locas) {
if (err) return handleError(err);

var returnArray = [];
for(var i = 0; i<locas.length;i++){
for(var j = 0; j<locas[i].subsectionList.length;j++){
for(var k = 0; k<locas[i].subsectionList[j].sensorList.length;k++){
if(locas[i].subsectionList[j].sensorList[k]._id == 'sensor1')
returnArray.push(locas[i].subsectionList[j].sensorList[k]);
}
}
}
console.log(returnArray);
});

enter image description here

关于node.js - 如何使用 mongoose 和 Node.js 只检索 Azure Cosmos 中的子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54722796/

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