我有一个类似的架构:
const FeedSchema = new Schema({
// ...
posts: {
type: [{
type: ObjectId,
ref: 'post',
}],
},
}, {
toObject: { getters: true, virtuals: true },
toJSON: { getters: true, virtuals: true },
});
当我运行一个试图获取postCount
虚拟(如下)的查询时,该查询无法正常工作。
FeedSchema.virtual('postCount').get(function () {
// console.log(this.title) <--- works fine
// console.log(this.posts) <--- undefined
return this.posts.length;
});
为什么this.posts
是undefined
?我怀疑这与引用数组有关。
这样,正确的方法是什么?
更新:
此函数试图获取一个Feed的详细信息:
async function getFeedShallow({ url }) {
try {
const shallowFeed = await this.findOne({ url }).select('-_id url title postCount');
console.log(shallowFeed);
return shallowFeed;
} catch (err) {
throw new Error(err.message);
}
}
答案 0 :(得分:0)
对于将来的访客,将功能更改为此可以解决问题:
async function getFeedShallow({ url }) {
try {
const shallowFeed = await this.findOne({ url }).select('-_id');
return shallowFeed;
} catch (err) {
throw new Error(err.message);
}
}