Node.js 如何仅在使用mongoose指定时检索字段?
我有客户模式:Node.js 如何仅在使用mongoose指定时检索字段?,node.js,mongoose,Node.js,Mongoose,我有客户模式: var CustomerSchema = new mongoose.Schema({ name: { type: String, required: true }, lastname: { type: String, required: true }, comment: { type: String } }, { toJSON: { virtuals: true }, toObject: { virtuals
var CustomerSchema = new mongoose.Schema({
name: { type: String, required: true },
lastname: { type: String, required: true },
comment: { type: String }
}, {
toJSON: { virtuals: true },
toObject: { virtuals: true }
});
const Customer = mongoose.model('Customer', CustomerSchema);
我想添加返回name+lastname的fullname字段
但默认情况下,全名不应仅在指定字段时返回,类似于populate函数
例如:
const c = Customer.find().populate('fullname'); // c.fullname
如何处理猫鼬
**编辑**
我尝试使用虚拟设备来实现这一点:
CustomerSchema.virtual('fullname').get(() => {
return 'some';
});
但我得到了一个错误:
If you are populating a virtual, you must set the localField and foreignField
检查我做过的这个问题,但我不需要localField或foreignField。通过设置
toObject:{virtuals:true},toJSON:{virtuals:true}
forCustomerSchema
I创建了virtuals,解决了只需要一个函数的问题,但错误消息相同。我还能做什么?这太奇怪了。对我来说,所有的一切看起来都符合mongoose文档的要求,应该可以正常工作。尝试在上打开一个问题