spring-projects / spring-projects/spring-data-mongodb

_class not inserted when using with Custom Converter

Open
#4,230 7 comments 0 reactions 1 assignee View on GitHub

Nobody has claimed this yet.

status: feedback-provided status: waiting-for-triage
Dominant language
Java
Stars
1.7k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

Hi,

I'm not quite sure if this is a bug, or I missed out certain configuration.

I have a reproduce ready at Github

In summary, I have a document

@TypeAlias("cinfo")
@Document("cinfo")
public class CInfo implements ReferenceAble {}

Where I register the converter

@Configuration
public class MongoConfig {
    @Bean
    MongoCustomConversions conversions() {
        return new MongoCustomConversions(List.of(new ReferenceAbleConverter()));
    }
}

The converter is just a simple @WritingConverter

@WritingConverter
public class ReferenceAbleConverter implements Converter<ReferenceAble, DocumentPointer<Document>> {

    @Override
    public DocumentPointer<Document> convert(ReferenceAble source) {
        return source::toReference;
    }

}

When I run the test

@DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
@Import(MongoConfig.class)
public class DocRefTests {
    @Autowired
    private CInfoRepository cInfoRepository;

    @Test
    void test1() {
        CInfo cInfo = CInfo.builder().cinfo("cinfo").build();
        CInfo createdCInfo = this.cInfoRepository.insert(cInfo);

        log.info("{}", createdCInfo);
    }
}

The log shows the following

2022-11-14 22:53:21.837 DEBUG 9512 --- [           main] o.s.data.mongodb.core.MongoTemplate      : Inserting Document containing fields: [cinfo] in collection: cinfo

{
    _id: ObjectId('6372531b8e27062bdd80046f'),
    cinfo: 'cinfo'
}

But if I don't import MongoConfig.class, then the output would be

2022-11-14 22:54:05.211 DEBUG 28056 --- [           main] o.s.data.mongodb.core.MongoTemplate      : Inserting Document containing fields: [cinfo, _class] in collection: cinfo

{
    _id: ObjectId('63725335c2a1c4466a4fdf38'),
    cinfo: 'cinfo',
    _class: 'cinfo'
}

Notice that _class is not being inserted to the document in the first test

Thanks!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.