【问题标题】:Grab object from MongoDB but limit number of items pulled from array从 MongoDB 抓取对象,但限制从数组中提取的项目数
【发布时间】:2015-04-01 17:46:20
【问题描述】:

我的 API 目前有一个从我的 MongoDB 数据库中获取事件的路由,基于 event_id。这工作正常。但是,我在此事件对象中有一个“照片”数组,该数组正在增长(目前该数组中有超过 3,000 个对象)。 我想传递一个limit 参数来限制从该数组中提取的结果数量,但无法弄清楚如何。以下是我当前的节点路由和 mongoDB 架构:

路线:

// get event by _id
app.get('/api/events/:event_id', function(req, res) {

    // use mongoose to get event
    Event.findOne({object_id: req.params.event_id}, function(err, event) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err)
            res.send(err)

        if (req.params.limit >= 0) {
            // res.jsonp(event) with photos array limited to req.params.limit
        }

        res.jsonp(event); // return event in JSON format
    });
});

架构:

var eventSchema = new Schema({
event: String,
city: String,
state: String,
date: String,
start: String,
end: String,
dateState: String,
radius: String,
team_1: String,
team_2: String,
object_id: String,
longitude: String,
latitude: String,
cover: {
    img: String,
    username: String
},
photos: []

})

【问题讨论】:

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:
Event.findOne({object_id: req.params.event_id})
    .limit(10)
    .exec(function(e,doc){
        ...
});

编辑

或者,如果您在照片上有 ref... 您可以使用 limit 选项填充引用 id 的 doc 数组。希望它有所帮助:) All abount population

.find(...)
.populate({
     path: 'photos',
     options: { limit: 5 }
})
.exec(...)

架构

var eventSchema = new Schema({
event: String,
city: String,
state: String,
...
photos: [{ type:String, ref:'pictureSchema' }]
}

var pictureSchema = new Schema({
name : {type:String},
url : {type:String},
...
}

在照片数组中,您只需输入图片文档的 id,当您填充照片数组时,它会将图片Sceham doc 设置为 _id。

【讨论】:

  • 我认为这种情况下的“限制”会限制返回的事件数量。我试图限制每个事件内的照片数组中的“照片”数量。不幸的是,更棘手。
  • 在你的问题上我看起来很快我很抱歉!
  • 哦,在我的公司里,我们总是将图片放在自己的模式中,因为它们独立于 eventSchema 保存信息。如果填充失败,您总是可以在 pictureSchema 中再次查找,然后 req.send({eventDoc: {}, pictureDoc: {})
【解决方案2】:

不要有一个不断增长的数组字段。这对性能不利,因为 MongoDB(好吧,如果

有一种方法可以限制查找查询中返回的数组元素的数量,使用$slice projection

> db.test.drop()
> db.test.insert({ "_id" : 0, "x" : [0, 1, 2, 3, 4] })
> db.test.find({ "_id" : 0 }, { "x" : { "$slice" : 2 } })
{ "_id" : 0, "x" : [0, 1] }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 2018-06-30
    • 2023-04-04
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多