Replies: 1 comment
-
It depends on how you call If you wait until const res = await Test.findOne().populate('clientTaxDetail');
await res.populate('clientTaxYearReportCount'); Below is a complete example: 'use strict';
const mongoose = require('mongoose');
const { Schema } = mongoose;
run().catch(err => console.log(err));
async function run() {
await mongoose.connect('mongodb://localhost:27017/test');
const schema = new Schema({
clientAccountId: String
});
schema.virtual('clientTaxDetail', {
foreignField: 'id',
localField: 'clientAccountId',
ref: 'TaxPayer',
justOne: true,
});
schema.virtual('clientTaxYearReportCount', {
foreignField: 'taxAccountId',
localField: 'clientAccountId',
ref: 'Report',
match: (doc) => ({ taxYear: doc.clientTaxDetail.taxYear, status: 'done' }),
count: true,
});
const Test = mongoose.model('Test', schema);
const TaxPayer = mongoose.model('TaxPayer', new Schema({
id: String,
taxYear: String,
clientAccountId: String
}));
const Report = mongoose.model('Report', new Schema({ taxAccountId: String, status: String, taxYear: String }));
await Report.create({ taxAccountId: 'testid1', status: 'done', taxYear: '2021' });
await TaxPayer.create({ id: 'testid2', taxYear: '2021', clientAccountId: 'testid1' });
await Test.create({ clientAccountId: 'testid2' });
const res = await Test.findOne().populate('clientTaxDetail');
await res.populate('clientTaxYearReportCount');
console.log(res.toObject({ virtuals: true }));
} Another alternative would be to make |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello, so wondering if this was possible or not, not having any luck. I'm running into an issue with one of the virtual fields on a schema.
We have set 2 virtuals on the schema, the first one relies on a document from a different collection and this is retrieving the document successfully. The issue is that the 2nd virtual (clientTaxYearReportCount) on the schema, uses a field that is returned from the first virtual in order to correctly populate the field. Added a snippet below to maybe better communicate the issue.
the virtual
clientTaxYearReportCount
uses theclientTaxDetail.taxYear
field to use to match documents from a different collection. When running, thematch
operation returnsclientTaxDetail
as undefined. Is there anyway to have the virtual fields available? I've tried adding { toJSON: true} and { toObject: true } but didn't help.Thank you!
Beta Was this translation helpful? Give feedback.
All reactions