如何在查找结果中使用mongoose virtuals
我在使用虚拟软件时遇到了一个非常棘手的问题。从下面的代码示例中可以看出,当我使用find时,为了让virtuals出现在结果中,我还必须包括创建virtuals的基列。除此之外还有其他选择吗?否则每次使用find时都必须同时选择base和virtuals如何在查找结果中使用mongoose virtuals,mongoose,Mongoose,我在使用虚拟软件时遇到了一个非常棘手的问题。从下面的代码示例中可以看出,当我使用find时,为了让virtuals出现在结果中,我还必须包括创建virtuals的基列。除此之外还有其他选择吗?否则每次使用find时都必须同时选择base和virtuals PersonSchema = new Schema({ fname: {type: String, required: true}, lname: String, bday: {type: Date, required:
PersonSchema = new Schema({
fname: {type: String, required: true},
lname: String,
bday: {type: Date, required: true},
share: mongoose.Decimal128,
},{toObject:{virtuals:true}, toJSON:{virtuals:true}});
PersonSchema.virtual('desc').get(function(){
const birth = this.bday.getMonth() + this.bday.getFullYear();
return this.fname + ' ' + this.lname + ' ' + this.share + '% ' ;
});
PersonSchema.virtual('Share').get(function(){ return this.share.toString});
const selectList = 'fname lname share bday desc Share';
PersonSchema.methods.getData = function() {
Persons.find({}, selectList, function(err, persons){
const data = JSON.parse(JSON.stringify(persons, {virtuals: true}));
console.log('persons', persons);
}).limit(5);
}
我看到您正在尝试在选项中设置虚拟对象的显示,您是否尝试过使用set方法
PersonSchema.set('toJSON', { virtuals: true });