gpt4 book ai didi

node.js - 使用 NodeJS 和 Mongoose 查询嵌入式文档

转载 作者:可可西里 更新时间:2023-11-01 10:44:45 26 4
gpt4 key购买 nike

我需要从mongodb查询以下数据:Project有很多Region,一个Region有很多Link

这是数据:

{ "_id" : ObjectId( "4f26a74f9416090000000003" ),
"description" : "A Test Project",
"regions" : [
{ "title" : "North America",
"_id" : ObjectId( "4f26a74f9416090000000004" ),
"links" : [
{ "title" : "A Really Cool Link" } ] },
{ "description" : "That Asia Place",
"title" : "Asia",
"_id" : ObjectId( "4f26b7283378ab0000000003" ),
"links" : [] },
{ "description" : "That South America Place",
"title" : "South America",
"_id" : ObjectId( "4f26e46b53f2f90000000003" ),
"links" : [] },
{ "description" : "That Australia Place",
"title" : "Australia",
"_id" : ObjectId( "4f26ea504fb2210000000003" ),
"links" : [] } ],
"title" : "Test" }

这是我的模型设置:

// mongoose
var Link = new Schema({
title : String
, href : String
, description : String
});

var Region = new Schema({
title : String
, description : String
, links : [Link]
});

var Project = new Schema({
title : String
, description : String
, regions : [Region]
});

mongoose.model('Link', Link);
mongoose.model('Region', Region);
mongoose.model('Project', Project);

var Link = mongoose.model('Link');
var Region = mongoose.model('Region');
var Project = mongoose.model('Project');

我遇到的问题是返回与 ID 匹配的单个区域对象。我可以返回所有区域及其各自的所有链接,但将其限制为 ID只是一个地区的问题。

这是我正在使用的中断路线:

app.get('/projects/:id/regions/:region_id', function(req, res){
Project.findById(req.param('id'), function(err, project) {
if (!err) {
project.regions.findById(req.params.region_id, function(err, region) {
if (!err) {
res.render('project_regions', {
locals: {
title: project.title,
project: project
}
});
}
});
} else {
res.redirect('/')
}
});
});

我知道上面的方法不起作用,因为“findById”返回的对象不响应 findByID,但它说明了我正在尝试做的事情。我尝试执行自定义查询,但它总是返回整个文档,而不是我想要的单个区域。

我也试过直接查询区域模式,但没有返回任何结果。我假设从作为子文档的模式查询,我必须根据上下文提供父文档是什么。

换句话说,以下不返回带有数据的“区域”对象:

app.get('/projects/:id/regions/:region_id', function(req, res){
Region.findById(req.params.region_id, function(err, region) {
if (!err) {
res.render('project_regions_show', {
locals: {
title: "test",
region: region
}
});
} else {
res.redirect('/')
}
});
});

感谢任何帮助。

最佳答案

星星,

您可以使用 query.select 阻止加载子文档:

即。

Entity.find({ ... })
.select({childentities: 0}) //excludes childentities
.exec(function(err, entities){
...
res.json({entities: entities});
});

关于node.js - 使用 NodeJS 和 Mongoose 查询嵌入式文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080222/

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