我想获取文档数组中的一个单个元素,而不获取整个数组本身。使用 Mongoose 可以做到这一点吗?
我尝试使用dot.notation但它似乎不起作用 - 它只是在“索引点”之后获取空的嵌套对象
// Here I'd like to get
// The first undo-ed item from the first board within my `boardBucket`
Room.findOne({name: this.name}, `boardBucket.items.0.undoedItems.1`, (err, result)=> {
if (err) throw err;
console.log(JSON.stringify(result, null, 4));
})
有什么办法可以实现这一点吗?
我想避免获取整个数组的原因
- 我的对象非常大,如果我将它们全部取回,将会导致内存问题
- 无论怎么看,它的效率都很低。
这是我的架构
,以防有帮助:
var roomSchema = new mongoose.Schema({
name: String,
boardBucket: {
currentBoardId: String,
items: [
{
boardId: String,
boardItems: Array,
undoedItems: Array, // <- Need to get a *single* element from this array
viewPosition: String
}
]
}
});
最佳答案
您可以使用 mongoose 提供的query
的slice
功能。浏览mongoose documentation on slice为了更好地理解。
According to the documentation:
slice([path], val)
Specifies a $slice projection for an array.
Parameters:
[path] <String> val <Number> number/range of elements to slice
尝试解决您的问题,我希望它有效:
Room.findOne({name: this.name})
.slice('boardBucket.items', 1)
.slice('boardBucket.items.undoedItems', [1,1])
.exec()
这将返回 items
数组的第一个元素,以及 undoedItems
的第二个元素。
关于node.js - Mongoose 仅返回文档嵌套数组中的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39025944/