spring data mongo reactive throw org.springframework.data.mapping.MappingException when eager loading nested @DbRef

huangapple go评论71阅读模式
英文:

spring data mongo reactive throw org.springframework.data.mapping.MappingException when eager loading nested @DbRef

问题

这是你提供的Java代码的中文翻译:

基本上我有一个包含对`UserPlot`(plots集合的@DbRef的`User`集合`UserPlot`我还有对`Plot`(plot@DbRef我的目标是找到所有用户并急切加载plots到`User`(还急切加载plot到UserPlot

@Data
@NoArgsConstructor
@Document(collection = "users")
public class User {

  @Id private String id;

  @Indexed(name = "ui_email", unique = true)
  private String email;

  private String password;

  @Indexed(name = "ui_first_name")
  private String firstName;

  @Indexed(name = "ui_last_name")
  private String lastName;

  @DBRef
  private List<UserPlot> plots;
}

@Data
@Document(collection = "users_have_plots")
public class UserPlot {

  @Id
  private String id;
  private String userId;

  @DBRef
  private Plot plot;
}

@Data
@Document(collection = "plots")
@NoArgsConstructor
public class Plot {

  @Id
  private String id;

  private Integer x;
  private Integer y;
}

@Repository
public interface UserRepository extends ReactiveMongoRepository<User, String> {

  @Aggregation(pipeline = {
      "{$lookup:{from:'users_have_plots',let:{plots:'$plots'},pipeline:[{$match:{$expr:{$in:['$_id',{$ifNull:'$$plots.$id',[]}]}}},{$lookup:{from:'plots',localField:'plot.$id',foreignField:'_id',as:'plot'}}],as:'plots'}}"
  })
  Flux<User> findAllIncludePlots();
}

@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class)
@EnableReactiveMongoRepositories
public class FarmApplication {

  public static void main(String[] args) {
    SpringApplication.run(FarmApplication.class, args);
  }

  @Bean
  CommandLineRunner t(UserRepository userRepository) {
    return a -> {
      userRepository.findAllIncludePlots().map(User::getPlots).doOnNext(System.out::println).subscribe();
    };
  }
}

你提到的错误信息似乎与数据转换问题有关,但代码本身看起来没有明显错误。你可以检查数据库中的数据,确保它们符合预期。你提供的示例数据表明你有相关的引用关系,但问题可能在于数据不匹配或者自定义转换器的设置不正确。在调试这个问题时,你可能需要查看数据库数据以确认它们的一致性,并检查MongoDB的版本和配置是否与代码兼容。

英文:

Basically, I have a User collection that contains a @DbRef to UserPlot (plots) collection. Inside UserPlot, I also have a @DbRef to Plot (plot). My goal is to find all users and eagerly load plots to User (also eagerly load plot to UserPlot)

@Data
@NoArgsConstructor
@Document(collection = &quot;users&quot;)
public class User {

  @Id private String id;

  @Indexed(name = &quot;ui_email&quot;, unique = true)
  private String email;

  private String password;

  @Indexed(name = &quot;ui_first_name&quot;)
  private String firstName;

  @Indexed(name = &quot;ui_last_name&quot;)
  private String lastName;
  
  @DBRef
  private List&lt;UserPlot&gt; plots;
}

@Data
@Document(collection = &quot;users_have_plots&quot;)
public class UserPlot {
  
  @Id
  private String id;
  private String userId;
  
  @DBRef
  private Plot plot;
}

@Data
@Document(collection = &quot;plots&quot;)
@NoArgsConstructor
public class Plot {
  
  @Id
  private String id;
  
  private Integer x;
  private Integer y;
}

@Repository
public interface UserRepository extends ReactiveMongoRepository&lt;User, String&gt; {
  
  @Aggregation(pipeline = {
      &quot;{$lookup:{from:&#39;users_have_plots&#39;,let:{plots:&#39;$plots&#39;},pipeline:[{$match:{$expr:{$in:[&#39;$_id&#39;,{$ifNull:[&#39;$$plots.$id&#39;,[]]}]}}},{$lookup:{from:&#39;plots&#39;,localField:&#39;plot.$id&#39;,foreignField:&#39;_id&#39;,as:&#39;plot&#39;}}],as:&#39;plots&#39;}}&quot;
  })
  Flux&lt;User&gt; findAllIncludePlots();
}

@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class)
@EnableReactiveMongoRepositories
public class FarmApplication {

  public static void main(String[] args) {
    SpringApplication.run(FarmApplication.class, args);
  }
  
  @Bean
  CommandLineRunner t(UserRepository userRepository) {
    return a -&gt; {
userRepository.findAllIncludePlots().map(User::getPlots).doOnNext(System.out::println).subscribe();
    };
  }
}

When I invoke userRepository.findAllIncludePlots().map(User::getPlots).doOnNext(System.out::println).subscribe(); then i get this error:

org.springframework.data.mapping.MappingException: Cannot convert [Document{{_id=6426b069ca83da130cdb7f70, x=0, y=0, _class=com.vilya.farm.domain.model.Plot}}] of type class java.util.ArrayList into an instance of class com.vilya.farm.domain.model.Plot; Implement a custom Converter&lt;class java.util.ArrayList, class com.vilya.farm.domain.model.Plot&gt; and register it with the CustomConversions; Parent object was: UserPlot(id=6426b073ca83da130cdb7f71, userId=6412c76956d4170a7de34d92, plot=null) -&gt; User(id=6412c76956d4170a7de34d92, email=abc@abc.com, password=$2a$10$s9VgOYd.fOKZF66TnAsjWemiCYkA7aG45NJpuSNgbVxpcIGF7fWqu, firstName=f, lastName=l, plots=null) -&gt; null
Caused by: org.springframework.data.mapping.MappingException: Cannot convert [Document{{_id=6426b069ca83da130cdb7f70, x=0, y=0, _class=com.vilya.farm.domain.model.Plot}}] of type class java.util.ArrayList into an instance of class com.vilya.farm.domain.model.Plot; Implement a custom Converter&lt;class java.util.ArrayList, class com.vilya.farm.domain.model.Plot&gt; and register it with the CustomConversions; Parent object was: UserPlot(id=6426b073ca83da130cdb7f71, userId=6412c76956d4170a7de34d92, plot=null) -&gt; User(id=6412c76956d4170a7de34d92, email=abc@abc.com, password=$2a$10$s9VgOYd.fOKZF66TnAsjWemiCYkA7aG45NJpuSNgbVxpcIGF7fWqu, firstName=f, lastName=l, plots=null) -&gt; null
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$DefaultConversionContext.convert(MappingMongoConverter.java:2292) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$ConversionContext.convert(MappingMongoConverter.java:2131) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1900) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getValueInternal(MappingMongoConverter.java:1359) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.lambda$getDbRefResolverCallback$1(MappingMongoConverter.java:632) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.DefaultDbRefResolverCallback.resolve(DefaultDbRefResolverCallback.java:57) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.DefaultDbRefResolver.resolveDbRef(DefaultDbRefResolver.java:85) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readAssociation(MappingMongoConverter.java:673) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readProperties(MappingMongoConverter.java:597) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.populateProperties(MappingMongoConverter.java:535) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:513) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readDocument(MappingMongoConverter.java:477) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$DefaultConversionContext.convert(MappingMongoConverter.java:2325) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$ConversionContext.convert(MappingMongoConverter.java:2131) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readCollectionOrArray(MappingMongoConverter.java:1402) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$DefaultConversionContext.convert(MappingMongoConverter.java:2297) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$AssociationConversionContext.convert(MappingMongoConverter.java:2208) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$ConversionContext.convert(MappingMongoConverter.java:2131) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1900) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getValueInternal(MappingMongoConverter.java:1359) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.lambda$getDbRefResolverCallback$1(MappingMongoConverter.java:632) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.DefaultDbRefResolverCallback.resolve(DefaultDbRefResolverCallback.java:57) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.DefaultDbRefResolver.resolveDbRef(DefaultDbRefResolver.java:85) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readAssociation(MappingMongoConverter.java:673) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readProperties(MappingMongoConverter.java:597) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.populateProperties(MappingMongoConverter.java:535) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:513) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readDocument(MappingMongoConverter.java:477) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:413) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:409) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:121) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at org.springframework.data.mongodb.core.ReactiveMongoTemplate$ReadDocumentCallback.doWith(ReactiveMongoTemplate.java:2914) ~[spring-data-mongodb-4.0.0.jar:4.0.0]
at reactor.core.publisher.FluxConcatMapNoPrefetch$FluxConcatMapNoPrefetchSubscriber.onNext(FluxConcatMapNoPrefetch.java:183) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.FluxCreate$BufferAsyncSink.drain(FluxCreate.java:814) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.FluxCreate$BufferAsyncSink.next(FluxCreate.java:739) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.FluxCreate$SerializedFluxSink.next(FluxCreate.java:161) ~[reactor-core-3.5.0.jar:3.5.0]
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511) ~[na:na]
at com.mongodb.reactivestreams.client.internal.BatchCursorFlux.lambda$recurseCursor$4(BatchCursorFlux.java:98) ~[mongodb-driver-reactivestreams-4.8.0.jar:na]
at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:171) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:180) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.FluxPeekFuseable$PeekConditionalSubscriber.onNext(FluxPeekFuseable.java:854) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoCreate$DefaultMonoSink.success(MonoCreate.java:172) ~[reactor-core-3.5.0.jar:3.5.0]
at com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.lambda$sinkToCallback$31(MongoOperationPublisher.java:577) ~[mongodb-driver-reactivestreams-4.8.0.jar:na]
at com.mongodb.internal.operation.AsyncQueryBatchCursor.next(AsyncQueryBatchCursor.java:173) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.reactivestreams.client.internal.BatchCursor.lambda$next$0(BatchCursor.java:38) ~[mongodb-driver-reactivestreams-4.8.0.jar:na]
at reactor.core.publisher.MonoCreate.subscribe(MonoCreate.java:58) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.Mono.subscribe(Mono.java:4444) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.Mono.subscribeWith(Mono.java:4510) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.Mono.subscribe(Mono.java:4272) ~[reactor-core-3.5.0.jar:3.5.0]
at com.mongodb.reactivestreams.client.internal.BatchCursorFlux.recurseCursor(BatchCursorFlux.java:108) ~[mongodb-driver-reactivestreams-4.8.0.jar:na]
at com.mongodb.reactivestreams.client.internal.BatchCursorFlux.lambda$subscribe$0(BatchCursorFlux.java:60) ~[mongodb-driver-reactivestreams-4.8.0.jar:na]
at reactor.core.publisher.LambdaMonoSubscriber.onNext(LambdaMonoSubscriber.java:171) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:122) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:82) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:82) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondComplete(MonoFlatMap.java:245) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:305) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:180) ~[reactor-core-3.5.0.jar:3.5.0]
at reactor.core.publisher.MonoCreate$DefaultMonoSink.success(MonoCreate.java:172) ~[reactor-core-3.5.0.jar:3.5.0]
at com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.lambda$sinkToCallback$31(MongoOperationPublisher.java:577) ~[mongodb-driver-reactivestreams-4.8.0.jar:na]
at com.mongodb.reactivestreams.client.internal.OperationExecutorImpl.lambda$execute$2(OperationExecutorImpl.java:94) ~[mongodb-driver-reactivestreams-4.8.0.jar:na]
at com.mongodb.internal.async.ErrorHandlingResultCallback.onResult(ErrorHandlingResultCallback.java:46) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.function.AsyncCallbackSupplier.lambda$whenComplete$1(AsyncCallbackSupplier.java:97) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.function.RetryingAsyncCallbackSupplier$RetryingCallback.onResult(RetryingAsyncCallbackSupplier.java:116) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.ErrorHandlingResultCallback.onResult(ErrorHandlingResultCallback.java:46) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.function.AsyncCallbackSupplier.lambda$whenComplete$1(AsyncCallbackSupplier.java:97) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.ErrorHandlingResultCallback.onResult(ErrorHandlingResultCallback.java:46) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.function.AsyncCallbackSupplier.lambda$whenComplete$1(AsyncCallbackSupplier.java:97) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.operation.CommandOperationHelper.lambda$transformingReadCallback$10(CommandOperationHelper.java:332) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.ErrorHandlingResultCallback.onResult(ErrorHandlingResultCallback.java:46) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.DefaultServer$DefaultServerProtocolExecutor$1.onResult(DefaultServer.java:242) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.ErrorHandlingResultCallback.onResult(ErrorHandlingResultCallback.java:46) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.CommandProtocolImpl$1.onResult(CommandProtocolImpl.java:84) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection$1.onResult(DefaultConnectionPool.java:683) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.UsageTrackingInternalConnection$2.onResult(UsageTrackingInternalConnection.java:159) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.async.ErrorHandlingResultCallback.onResult(ErrorHandlingResultCallback.java:46) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$2$1.onResult(InternalStreamConnection.java:524) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$2$1.onResult(InternalStreamConnection.java:501) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback$MessageCallback.onResult(InternalStreamConnection.java:824) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback$MessageCallback.onResult(InternalStreamConnection.java:788) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:648) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:645) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.connection.netty.NettyStream.readAsync(NettyStream.java:319) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.connection.netty.NettyStream.readAsync(NettyStream.java:266) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.readAsync(InternalStreamConnection.java:645) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.access$600(InternalStreamConnection.java:89) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback.onResult(InternalStreamConnection.java:778) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback.onResult(InternalStreamConnection.java:763) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:648) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:645) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.connection.netty.NettyStream.readAsync(NettyStream.java:319) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.connection.netty.NettyStream.handleReadResponse(NettyStream.java:347) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.connection.netty.NettyStream.access$1100(NettyStream.java:105) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.connection.netty.NettyStream$InboundBufferHandler.channelRead0(NettyStream.java:421) ~[mongodb-driver-core-4.8.0.jar:na]
at com.mongodb.connection.netty.NettyStream$InboundBufferHandler.channelRead0(NettyStream.java:418) ~[mongodb-driver-core-4.8.0.jar:na]
at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) ~[netty-transport-4.1.85.Final.jar:4.1.85.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) ~[netty-common-4.1.85.Final.jar:4.1.85.Final]
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.85.Final.jar:4.1.85.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.85.Final.jar:4.1.85.Final]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

I think there is a problem with my @Aggregation but I cannot find out the reason. Please help. Thank you

EDIT: my data looks like

vilya_be&gt; db.plots.find({})
[
{
_id: ObjectId(&quot;6426b069ca83da130cdb7f70&quot;),
x: 0,
y: 0,
_class: &#39;com.vilya.farm.domain.model.Plot&#39;
}
]
vilya_be&gt; db.users_have_plots.find({})
[
{
_id: ObjectId(&quot;6426b073ca83da130cdb7f71&quot;),
userId: &#39;6412c76956d4170a7de34d92&#39;,
plot: DBRef(&quot;plots&quot;, ObjectId(&quot;6426b069ca83da130cdb7f70&quot;)),
_class: &#39;com.vilya.farm.domain.model.UserPlot&#39;
}
]
vilya_be&gt; db.users.find({})
[
{
_id: ObjectId(&quot;6412c76956d4170a7de34d92&quot;),
email: &#39;abc@abc.com&#39;,
password: &#39;$2a$10$s9VgOYd.fOKZF66TnAsjWemiCYkA7aG45NJpuSNgbVxpcIGF7fWqu&#39;,
firstName: &#39;f&#39;,
lastName: &#39;l&#39;,
plots: [ DBRef(&quot;users_have_plots&quot;, ObjectId(&quot;6426b073ca83da130cdb7f71&quot;)) ],
_class: &#39;com.vilya.farm.domain.model.User&#39;
},
{
_id: ObjectId(&quot;6414667360e4ba4481052627&quot;),
email: &#39;abc1@abc.com&#39;,
password: &#39;$2a$10$OP52phZ61l2JX2e2TQOu9ubYFBYcPeqEZ92ox2Nyyp5e.MEZk7GhS&#39;,
firstName: &#39;f&#39;,
lastName: &#39;l&#39;,
_class: &#39;com.vilya.farm.domain.model.User&#39;
}
]

mongo version: mongo:6.0.2-focal running on docker desktop

答案1

得分: 1

错误提示您收到了一个数组而不是一个对象的情况,这发生在"plot"键上。如果您检查您的文档"UserPlot",您会发现"Plot"是一个属性,而不是一个数组。因此,第二次查找操作返回一个数组。

所以,您需要使用$unwind来在聚合操作中将数组转换为对象。由于我们始终只有一个plot,所以可以使用它。$unwind文档

更新后的聚合操作:

{$lookup:{from:&#39;users_have_plots&#39;,let:{plots:&#39;$plots&#39;},pipeline:[{$match:{$expr:{$in:[&#39;$_id&#39;,{$ifNull:[&#39;$$plots.$id&#39;,[]]}]}}},{$lookup:{from:&#39;plots&#39;,localField:&#39;plot.$id&#39;,foreignField:&#39;_id&#39;,as:&#39;plot&#39;}},{$unwind: &#39;$plot&#39;}],as:&#39;plots&#39;}}

给出了plot中的对象结果:

[
  {
    _id: ObjectId(&quot;6412c76956d4170a7de34d92&quot;),
    email: &#39;abc@abc.com&#39;,
    password: &#39;$2a$10$s9VgOYd.fOKZF66TnAsjWemiCYkA7aG45NJpuSNgbVxpcIGF7fWqu&#39;,
    firstName: &#39;f&#39;,
    lastName: &#39;l&#39;,
    plots: [
      {
        _id: ObjectId(&quot;6426b073ca83da130cdb7f71&quot;),
        userId: &#39;6412c76956d4170a7de34d92&#39;,
        plot: {
          _id: ObjectId(&quot;6426b069ca83da130cdb7f70&quot;),
          x: 0,
          y: 0,
          _class: &#39;com.vilya.farm.domain.model.Plot&#39;
        },
        _class: &#39;com.vilya.farm.domain.model.UserPlot&#39;
      }
    ],
    _class: &#39;com.vilya.farm.domain.model.User&#39;
  },
  {
    _id: ObjectId(&quot;6414667360e4ba4481052627&quot;),
    email: &#39;abc1@abc.com&#39;,
    password: &#39;$2a$10$OP52phZ61l2JX2e2TQOu9ubYFBYcPeqEZ92ox2Nyyp5e.MEZk7GhS&#39;,
    firstName: &#39;f&#39;,
    lastName: &#39;l&#39;,
    _class: &#39;com.vilya.farm.domain.model.User&#39;,
    plots: []
  }
]
英文:

> type class java.util.ArrayList into an instance of class com.vilya.farm.domain.model.Plot;

The error says that you are getting an array instead of an object at the plot key. If you check your document UserPlot you have Plot as a property, not an array. So aggregation from the second lookup is returning an array.

So, you need to use $unwind to convert the array to an object in aggregation. As, we have always 1 plot so we can use that. $unwind documentation

Updated Aggregation:

{$lookup:{from:&#39;users_have_plots&#39;,let:{plots:&#39;$plots&#39;},pipeline:[{$match:{$expr:{$in:[&#39;$_id&#39;,{$ifNull:[&#39;$$plots.$id&#39;,[]]}]}}},{$lookup:{from:&#39;plots&#39;,localField:&#39;plot.$id&#39;,foreignField:&#39;_id&#39;,as:&#39;plot&#39;}},{$unwind: &#39;$plot&#39;}],as:&#39;plots&#39;}}

Gives result an object in plot:

[
  {
    _id: ObjectId(&quot;6412c76956d4170a7de34d92&quot;),
    email: &#39;abc@abc.com&#39;,
    password: &#39;$2a$10$s9VgOYd.fOKZF66TnAsjWemiCYkA7aG45NJpuSNgbVxpcIGF7fWqu&#39;,
    firstName: &#39;f&#39;,
    lastName: &#39;l&#39;,
    plots: [
      {
        _id: ObjectId(&quot;6426b073ca83da130cdb7f71&quot;),
        userId: &#39;6412c76956d4170a7de34d92&#39;,
        plot: {
          _id: ObjectId(&quot;6426b069ca83da130cdb7f70&quot;),
          x: 0,
          y: 0,
          _class: &#39;com.vilya.farm.domain.model.Plot&#39;
        },
        _class: &#39;com.vilya.farm.domain.model.UserPlot&#39;
      }
    ],
    _class: &#39;com.vilya.farm.domain.model.User&#39;
  },
  {
    _id: ObjectId(&quot;6414667360e4ba4481052627&quot;),
    email: &#39;abc1@abc.com&#39;,
    password: &#39;$2a$10$OP52phZ61l2JX2e2TQOu9ubYFBYcPeqEZ92ox2Nyyp5e.MEZk7GhS&#39;,
    firstName: &#39;f&#39;,
    lastName: &#39;l&#39;,
    _class: &#39;com.vilya.farm.domain.model.User&#39;,
    plots: []
  }
]

huangapple
  • 本文由 发表于 2023年3月31日 18:15:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定