-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
populate() fails to reliably populate virtual fields in an embedded subdocument array, depending on the number of matches #12730
Labels
confirmed-bug
We've confirmed this is a bug in Mongoose and will fix it.
Milestone
Comments
IslandRhythms
added
needs clarification
This issue doesn't have enough information to be actionable. Close after 14 days of inactivity
and removed
needs clarification
This issue doesn't have enough information to be actionable. Close after 14 days of inactivity
labels
Nov 28, 2022
One problem I just noticed is that you're calling |
IslandRhythms
added
the
confirmed-bug
We've confirmed this is a bug in Mongoose and will fix it.
label
Nov 28, 2022
const mongoose = require('mongoose');
const shiftSchema = new mongoose.Schema({
employeeId: mongoose.Types.ObjectId,
startedAt: Date,
endedAt: Date
});
const Shift = mongoose.model('Shift', shiftSchema);
const employeeSchema = new mongoose.Schema({
name: String,
}, {toJSON: {virtuals: true}, toObject: {virtuals: true}});
employeeSchema.virtual('mostRecentShift', {
ref: Shift,
localField: '_id',
foreignField: 'employeeId',
options: {
sort: { startedAt: -1 },
},
justOne: true,
});
const storeSchema = new mongoose.Schema({
location: String,
employees: [employeeSchema],
});
const Store = mongoose.model('Store', storeSchema)
async function run() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
const store = await Store.create({
location: 'Tashbaan',
employees: [
{ name: 'Aravis' },
{ name: 'Shasta' },
],
});
const employeeAravis = store.employees.find(({ name }) => name === 'Aravis');
const employeeShasta = store.employees.find(({ name }) => name === 'Shasta');
console.log('is aravis aravis', employeeAravis)
console.log('is shasta shasta', employeeShasta)
await Shift.insertMany([
{ employeeId: employeeAravis._id, startedAt: new Date(Date.now() - 57600000), endedAt: new Date(Date.now() - 43200000) },
{ employeeId: employeeAravis._id, startedAt: new Date(Date.now() - 28800000), endedAt: new Date(Date.now() - 14400000) },
{ employeeId: employeeShasta._id, startedAt: new Date(Date.now() - 14400000), endedAt: new Date() },
])
const storeWithMostRecentShifts = await Store.findOne({ location: 'Tashbaan' })
.populate('employees.mostRecentShift')
.select('-__v');
// Even though shifts exist for both Aravis and Shasta, Shasta's mostRecentShift is NOT populated
console.log('When Aravis has 2 shifts and Shasta has 1 shift')
console.log(JSON.stringify(storeWithMostRecentShifts.toJSON({ virtuals: true }).employees, null, 4));
// Now I remove Aravis's oldest shift, so that her mostRecentShift does not change
console.log('original shift', await Shift.find({ employeeId: employeeAravis._id }))
const Shifts = await Shift.find({ employeeId: employeeAravis._id }).sort({ startedAt: 1 });
const removedShift = await Shift.findByIdAndDelete({ _id: Shifts[0]._id });
console.log('removedShift', removedShift);
console.log('remaining shifts', await Shift.find());
// Re-populating mostRecentShift
const storeWithMostRecentShiftsNew = await Store.findOne({ location: 'Tashbaan' })
.populate('employees.mostRecentShift')
.select('-__v');
// Now, mostRecentShift is populated for both employees
console.log('When both employees have 1 shift each')
console.log(JSON.stringify(storeWithMostRecentShiftsNew.toJSON({ virtuals: true }).employees, null, 4));
}
run();
|
vkarpov15
added a commit
that referenced
this issue
Dec 19, 2022
fix(populate): handle virtual populate underneath document array withjustOne=true and sort set where 1 element has only 1 result
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prerequisites
Mongoose version
6.7.3
Node.js version
16.14
MongoDB server version
5.0
Typescript version (if applicable)
No response
Description
I have a model
Store
with an array propertyemployees
where each element is a nested schemaEmployeeSchema
. I have another modelShift
which contains details of the shifts for every employee. The schemaEmployeeSchema
has a virtual calledmostRecentShift
withShift
as a reference.When calling
store.populate('employees.mostRecentShift')
, even though matching documents always exist for themostRecentShift
, depending on the number of matches, it may or may not be populated.Steps to Reproduce
The following code shows the behavior of populate in two cases:
Output:
Expected Behavior
mostRecentShift
to have been populated for both employees in both cases.Expected output:
The text was updated successfully, but these errors were encountered: