繁体   English   中英

猫鼬填充一个虚拟而不是整个模式

[英]Mongoose populate a virtual instead of the entire Schema

我正在尝试.populate特定模型,但是如果它是虚拟的 ,似乎它会忽略第二个select命令。

// This won't work - it just returns the _id meaning it didn't populate
.populate({ path: 'user', select: 'post' }) // Post is a : virtual('post')
.populate('user', 'post') // Also doesn't work

// If I manually select all the fields the virtual does, that works of course
.populate({ path: 'user', select: '_id name image type' })

这是我在User对象上创建的虚拟对象

// Here's the relating parts of the Model

var UserSchema = new Schema({
    name : String,
    type: {},
    image : String
});

// Here's the virtual
UserSchema
.virtual('post')
.get(function () {
    return {
        '_id' : this._id,
        'name' : this.name,
        'type' : this.type,
        'image' : this.image
    };
});

我一定想念一些东西...阅读文档,一切似乎都很好。

猫鼬没有承诺用选择的属性来填充虚拟机,文档也没有说明。 看来,一般是手动工作的。

您可以在UserScheme上创建适合于情况的常量变量,而不是使用virtual。 它可以返回select的字符串。

UserScheme.getPostFields = "_id name image type"; // under UserScheme
// pass on select method
.populate({ path: 'user', select: UserScheme.getPostFields });

这种方法可能很奇怪,但是如果需要,您也可以动态地更改这种情况。

顺便说一句,在这种情况下,有一个适用于npm的猫鼬-人口-虚拟动物

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM