Skip to content
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

Populating unset field which type is array of objects results in an array with one empty object #8432

Closed
alexeychikk opened this issue Dec 16, 2019 · 3 comments
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@alexeychikk
Copy link

alexeychikk commented Dec 16, 2019

Do you want to request a feature or report a bug?
bug

What is the current behavior?
Populating unset field which type is array of objects results in an array with one empty object (or object whose fields are all nulls).

If the current behavior is a bug, please provide the steps to reproduce.

https://github.com/alexeychikk/mongoose-populate-array-bug
npm install
npm start

You should notice files: [ { "uploadedBy": null, "id": null } ] in the populated rides. Issue is gone if you comment out await Ride.updateMany({}, { $unset: { files: 1 } });

What is the expected behavior?
Field should be populated with default value or remain empty.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

Node 10.14
mongodb 3.4.0
mongoose 5.8.1

@AbdelrahmanHafez
Copy link
Collaborator

Not sure why this happens, but it's worth noting that this happens only when using virtuals.

In the code below, changing the populate path to
path: 'files.uploaderId' instead of path: 'files.uploadedBy' changes the behavior.

const mongoose = require('mongoose');
const { Schema } = require('mongoose');

const url = 'mongodb://127.0.0.1:27017/test';
mongoose.connect(url, { useNewUrlParser: true });

const companySchema = new Schema({ name: { type: String, required: true } });

const userSchema = new Schema({
  fullName: { type: String, required: true },
  companyId: { type: Schema.Types.ObjectId, ref: 'Company', required: true }
});

const fileSchema = new Schema({
  _id: { type: String, required: true },
  uploaderId: { type: Schema.Types.ObjectId, ref: 'User', required: true }
}, { _id: false, toObject: { virtuals: true }, toJSON: { virtuals: true } });

fileSchema.virtual('uploadedBy', { ref: 'User', localField: 'uploaderId', foreignField: '_id', justOne: true });

const rideSchema = new Schema({
  title: { type: String, required: true },
  files: { type: [fileSchema], default: [] }
}, { toObject: { virtuals: true }, toJSON: { virtuals: true } });

const User = mongoose.model('User', userSchema);
const Company = mongoose.model('Company', companySchema);
const Ride = mongoose.model('Ride', rideSchema);



async function run () {

  await Promise.all([
    Ride.deleteMany({}),
    User.deleteMany({}),
    Company.deleteMany({})
  ]);


  const company = new Company({ name: 'Apple' });
  const user = new User({ fullName: 'John Doe', companyId: company._id });
  const ride = new Ride({
    title: 'Berlin-Moscow',
    files: [{ _id: '123', uploaderId: user._id }]
  });

  await Promise.all([
    user.save(),
    company.save(),
    ride.save()
  ]);


  await Ride.updateMany({}, { $unset: { files: 1 } });

  const foundRide = await Ride.findOne()
    .populate({
      path: 'files.uploadedBy',
      justOne: true,
      populate: {
        path: 'companyId',
        justOne: true
      }
    });

  console.log(foundRide.files);
}

run().catch(console.error);

@alexeychikk
Copy link
Author

@AbdelrahmanHafez In your code snippet you still populating files.uploadedBy but you call Ride.findOne() instead of Ride.find().

@alexeychikk
Copy link
Author

@AbdelrahmanHafez Also, I can't populate uploaderId because in the original code ride is saved after it is populated, and if user is not found then uploaderId: null and an error occurs while saving because uploaderId is required field.

@vkarpov15 vkarpov15 added this to the 5.8.2 milestone Dec 20, 2019
@vkarpov15 vkarpov15 added the has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue label Dec 20, 2019
@vkarpov15 vkarpov15 modified the milestones: 5.8.2, 5.8.3 Dec 20, 2019
vkarpov15 added a commit that referenced this issue Dec 21, 2019
@vkarpov15 vkarpov15 added confirmed-bug We've confirmed this is a bug in Mongoose and will fix it. and removed has repro script There is a repro script, the Mongoose devs need to confirm that it reproduces the issue labels Dec 21, 2019
vkarpov15 added a commit that referenced this issue Dec 30, 2019
vkarpov15 added a commit that referenced this issue Dec 30, 2019
vkarpov15 added a commit that referenced this issue Jun 16, 2020
…onal populate is nested under a virtual populate like #8432
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Projects
None yet
Development

No branches or pull requests

3 participants