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

Nested population restoration on hydration a model #15110

Open
2 tasks done
yamaha252 opened this issue Dec 17, 2024 · 1 comment
Open
2 tasks done

Nested population restoration on hydration a model #15110

yamaha252 opened this issue Dec 17, 2024 · 1 comment
Labels
confirmed-bug We've confirmed this is a bug in Mongoose and will fix it.
Milestone

Comments

@yamaha252
Copy link

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.9.1

Node.js version

20.16.0

MongoDB server version

5.0.2

Typescript version (if applicable)

5.7.2

Description

On hydrating (with enabled hydratedPopulatedDocs option) a model has deep nested populated data, on second and next levels it applies in a raw condition without hydration.

Steps to Reproduce

const ArticleSchema = new Schema({
  title: {
    type: String
  }
});

const StorySchema = new Schema({
  title: {
    type: String
  },
  article: {
    type: Schema.Types.ObjectId,
    ref: 'Article'
  }
});

const UserSchema = new Schema({
  name: String,
  stories: [{
    type: Schema.Types.ObjectId,
    ref: 'Story'
  }]
});

db.deleteModel(/User/);
db.deleteModel(/Story/);
db.deleteModel(/Article/);

const User = db.model('User', UserSchema);
const Story = db.model('Story', StorySchema);
const Article = db.model('Article', ArticleSchema);

const article = await Article.create({ title: 'Cinema' });
const story1 = await Story.create({ title: 'Ticket 1', article });
const story2 = await Story.create({ title: 'Ticket 2' });

await User.create({ name: 'Alex', stories: [story1, story2] });

const populated = await User.findOne({ name: 'Alex' }).populate({
  path: 'stories',
  populate: ['article']
}).lean();

const hydrated = User.hydrate(
  JSON.parse(JSON.stringify(populated)),
  null,
  { hydratedPopulatedDocs: true }
);

assert.ok(hydrated.populated('stories'));

assert.ok(hydrated.stories[0].populated('article'));
assert.equal(hydrated.stories[0].article._id.toString(), article._id.toString());
assert.ok(typeof hydrated.stories[0].article._id === 'object');
assert.ok(hydrated.stories[0].article._id instanceof mongoose.Types.ObjectId);
assert.equal(hydrated.stories[0].article.title, 'Cinema');

assert.ok(!hydrated.stories[1].article);

Virtuals populated hydration:

const ArticleSchema = new Schema({
  title: {
    type: String
  }
});

const StorySchema = new Schema({
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  title: {
    type: String
  },
  article: {
    type: Schema.Types.ObjectId,
    ref: 'Article'
  }
});

const UserSchema = new Schema({
  name: String
});

UserSchema.virtual('stories', {
  ref: 'Story',
  localField: '_id',
  foreignField: 'userId'
});

db.deleteModel(/User/);
db.deleteModel(/Story/);
db.deleteModel(/Article/);

const User = db.model('User', UserSchema);
const Story = db.model('Story', StorySchema);
const Article = db.model('Article', ArticleSchema);

const article = await Article.create({ title: 'Cinema' });
const user = await User.create({ name: 'Alex' });
await Story.create({ title: 'Ticket 1', userId: user._id, article });
await Story.create({ title: 'Ticket 2', userId: user._id });

const populated = await User.findOne({ name: 'Alex' }).populate({
  path: 'stories',
  populate: ['article']
}).lean();

const hydrated = User.hydrate(
  JSON.parse(JSON.stringify(populated)),
  null,
  { hydratedPopulatedDocs: true }
);

assert.ok(hydrated.populated('stories'));

assert.ok(hydrated.stories[0].populated('article'));
assert.equal(hydrated.stories[0].article._id.toString(), article._id.toString());
assert.ok(typeof hydrated.stories[0].article._id === 'object');
assert.ok(hydrated.stories[0].article._id instanceof mongoose.Types.ObjectId);
assert.equal(hydrated.stories[0].article.title, 'Cinema');

assert.ok(!hydrated.stories[1].article);

Expected Behavior

Populated properties should be hydrated on all nested levels

@vkarpov15 vkarpov15 added this to the 8.9.2 milestone Dec 18, 2024
@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 18, 2024
@IslandRhythms IslandRhythms 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 18, 2024
@IslandRhythms
Copy link
Collaborator

const mongoose = require('mongoose');

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

(async() => {
    const db = await mongoose.connect('mongodb://localhost:27017/mongoose-test')
    
    try {
        await bug(db);
    } catch (err) {
        console.log('bug function')
        console.log(err);
    }

    try {
        await test(db)
    } catch(err) {
        console.log('test function')
        console.log(err)
    }
})();



async function bug(db) {
    const ArticleSchema = new Schema({
        title: {
          type: String
        }
      });
      
      const StorySchema = new Schema({
        title: {
          type: String
        },
        article: {
          type: Schema.Types.ObjectId,
          ref: 'Article'
        }
      });
      
      const UserSchema = new Schema({
        name: String,
        stories: [{
          type: Schema.Types.ObjectId,
          ref: 'Story'
        }]
      });
      
      db.deleteModel(/User/);
      db.deleteModel(/Story/);
      db.deleteModel(/Article/);
      
      const User = db.model('User', UserSchema);
      const Story = db.model('Story', StorySchema);
      const Article = db.model('Article', ArticleSchema);
      
      const article = await Article.create({ title: 'Cinema' });
      const story1 = await Story.create({ title: 'Ticket 1', article });
      const story2 = await Story.create({ title: 'Ticket 2' });
      
      await User.create({ name: 'Alex', stories: [story1, story2] });
      
      const populated = await User.findOne({ name: 'Alex' }).populate({
        path: 'stories',
        populate: ['article']
      }).lean();
      
      const hydrated = User.hydrate(
        JSON.parse(JSON.stringify(populated)),
        null,
        { hydratedPopulatedDocs: true }
      );
      
      assert.ok(hydrated.populated('stories'));
      
      assert.ok(hydrated.stories[0].populated('article'));
      assert.equal(hydrated.stories[0].article._id.toString(), article._id.toString());
      assert.ok(typeof hydrated.stories[0].article._id === 'object');
      assert.ok(hydrated.stories[0].article._id instanceof mongoose.Types.ObjectId);
      assert.equal(hydrated.stories[0].article.title, 'Cinema');
      
      assert.ok(!hydrated.stories[1].article);
}

async function test(db) {
    const ArticleSchema = new Schema({
        title: {
          type: String
        }
      });
      
      const StorySchema = new Schema({
        userId: {
          type: Schema.Types.ObjectId,
          ref: 'User'
        },
        title: {
          type: String
        },
        article: {
          type: Schema.Types.ObjectId,
          ref: 'Article'
        }
      });
      
      const UserSchema = new Schema({
        name: String
      });
      
      UserSchema.virtual('stories', {
        ref: 'Story',
        localField: '_id',
        foreignField: 'userId'
      });
      
      db.deleteModel(/User/);
      db.deleteModel(/Story/);
      db.deleteModel(/Article/);
      
      const User = db.model('User', UserSchema);
      const Story = db.model('Story', StorySchema);
      const Article = db.model('Article', ArticleSchema);
      
      const article = await Article.create({ title: 'Cinema' });
      const user = await User.create({ name: 'Alex' });
      await Story.create({ title: 'Ticket 1', userId: user._id, article });
      await Story.create({ title: 'Ticket 2', userId: user._id });
      
      const populated = await User.findOne({ name: 'Alex' }).populate({
        path: 'stories',
        populate: ['article']
      }).lean();
      
      const hydrated = User.hydrate(
        JSON.parse(JSON.stringify(populated)),
        null,
        { hydratedPopulatedDocs: true }
      );
      
      assert.ok(hydrated.populated('stories'));
      
      assert.ok(hydrated.stories[0].populated('article'));
      assert.equal(hydrated.stories[0].article._id.toString(), article._id.toString());
      assert.ok(typeof hydrated.stories[0].article._id === 'object');
      assert.ok(hydrated.stories[0].article._id instanceof mongoose.Types.ObjectId);
      assert.equal(hydrated.stories[0].article.title, 'Cinema');
      
      assert.ok(!hydrated.stories[1].article);
}

@vkarpov15 vkarpov15 modified the milestones: 8.9.2, 8.9.3 Dec 18, 2024
vkarpov15 added a commit that referenced this issue Dec 23, 2024
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