【发布时间】:2017-05-03 00:09:44
【问题描述】:
我有一个带有子文档的父架构。子文档有一个包含嵌入对象数组的属性:
子架构
var snippetSchema = new Schema({
snippet: [
{
language: String,
text: String,
_id: false
}
]
});
父架构
var itemSchema = new Schema({
lsin: Number,
identifier: {
isbn13: Number,
},
title: snippetSchema,
});
在Item.find 上返回一个像这样的对象:
[
{
_id: (...),
lsin: 676765,
identifier: {
isbn13: 8797734598763
},
title: {
_id: (...),
snippet: [
{
language: 'se',
text: 'Pippi Långstrump'
}
]
}
}
]
当对象返回给客户端时,我想跳过子文档的一层嵌套:
[
{
_id: (...),
lsin: 676765,
identifier: {
isbn13: 8797734598763
},
title: {
language: 'se',
text: 'Pippi Långstrump'
}
}
]
到目前为止我已经尝试过:
#1 使用 getter
function getter() {
return this.title.snippet[0];
}
var itemSchema = new Schema({
...
title: { type: snippetSchema, get: getter }
});
但它会创建一个无限循环,导致RangeError: Maximum call stack size exceeded。
#2 使用虚拟属性
var itemSchema = new Schema({
..., {
toObject: {
virtuals: true
}
});
itemSchema
.virtual('title2')
.get(function () {
return this.title.snippet[0];
});
这将生成所需的嵌套级别,但在新属性下,这是不可接受的。据我所知,没有办法用虚拟属性覆盖属性。
问题是:有没有其他方法可以得到想要的输出?在整个应用程序中会有多个对snippetSchema 的引用,并且首选 DRY 方法。
我是 MongoDB 和 Mongoose 的新手。
【问题讨论】:
标签: node.js mongodb mongoose subdocument