[CSHARP-2489] Error: Cannot deserialize a 'String' from BsonType 'Undefined. Created: 25/Jan/19  Updated: 27/Oct/23  Resolved: 28/Jan/19

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.7.3
Fix Version/s: None

Type: Task Priority: Blocker - P1
Reporter: charan Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

.net mvc core 2.0



 Description   

HI Team,

I Am using mongoDB in .net development where i have String "PBI001/INC000003257691" in a collection but it is throwing an error "Cannot deserialize a 'String' from BsonType 'Undefined".

Please provide me the resolution ASAP.



 Comments   
Comment by Robert Stam [ 05/Feb/19 ]

You basically have two options:

  1. Write a script or program to fix your documents
  2. Change your POCO to accept dirty data 

You can't write a program in C# using POCOs to fix your documents because they can't be deserialized as they are. You can either write a C# program using BsonDocument instead of POCOs to clean the data, or you can write a script in JavaScript that you can run in the MongoDB shell.

To change your POCO to accept dirty data you have to change the type of the field from string to BsonValue. A field of type BsonValue is capable of holding any BSON value at all, including strings and undefined. The downside to this approach is that you lose some of the benefits of using strongly typed C#.

My recommendation is to find and fix the documents that need fixing.

Comment by charan [ 05/Feb/19 ]

yes now how to resolve it

 

Comment by Robert Stam [ 28/Jan/19 ]

This error occurs when you are reading a document from the database and the destination field in your C# class is of type string but the corresponding field in the database document has a value of undefined.

For example, consider the following class:

public class C
{
    public int Id { get; set; }
    public string S { get; set; }
}

And suppose you have a document in the database that looks like this:

> db.test.find()
{ "_id" : 1, "S" : undefined }
>

Note that the value of "S" is undefined, when it should be a string (or maybe null).

The following code with the above sample document reproduces the exception you are seeing:

var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("test");
var collection = database.GetCollection<C>("test");
 
var document = collection.Find("{}").FirstOrDefault();

The error message should identify which field in your C# class could not be deserialized. For the sample repro above the error message is:

An error occurred while deserializing the S property of class TestCSharp2489.C: Cannot deserialize a 'String' from BsonType 'Undefined'.

 

 

Generated at Wed Feb 07 21:42:42 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.