LiteDB icon indicating copy to clipboard operation
LiteDB copied to clipboard

[BUG] new BsonValue(new string[] { "a", "b", "c" }).AsArray returns null

Open ericnewton76 opened this issue 1 year ago • 4 comments

Version checked 5.0.12, checked 5.0.19, (worked in 3.1.1)

Describe the bug Creating a new object via BsonValue ctor with an array for the value returns a BsonValue instance with Type=Array and RawValue=["a","b","c"] but usage of AsArray fail with null (returns this as BsonArray which returns null)

Code to Reproduce

var strings = new string[] { "a", "b", "c" };
var bsonValueOfArray = new BsonValue(strings);

Assert.NotNull(bsonValueOfArray.AsArray);

Expected behavior Assert.NotNull(new BsonValue(new string[] { "a", "b", "c" }).AsArray); to succeed

The problem becomes apparent in the Serialization code, where it sees a BsonValue with Type=Array, calls AsArray and causes a NullReferenceException

Of Note, I uncovered this specifically when using MongoDB.Bson (2.20) as a source:

//psuedocode atm
var mongoArray = new MongoDB.Bson.BsonArray({ "a", "b", "c" });

var doc=new LiteDB.BsonDocument();
doc["array"] = new LiteDB.BsonValue(mongoArray);
liteCollection.Add(doc); //fails at ([line 661 ](https://github.com/mbdavid/LiteDB/blob/f23f14c53e934e14d8cfd0f10a1d78d21b3b3deb/LiteDB/Document/BsonValue.cs#L661)

ericnewton76 avatar Mar 20 '24 18:03 ericnewton76

Since 3.1.1 worked, I went to https://github.com/mbdavid/LiteDB/blob/aecb2d66369af905e1febde5541e036e3618be16/LiteDB/Document/BsonValue.cs#L191 and see that AsArray is significantly different, in that it correctly returns a new LiteDB.BsonArray typed instance.

I tried to trace back to when AsArray changed so significantly but ran out of time.

Here's a test to show it failing:

namespace LiteDB.Tests.Issues;

public class Issue2456_Tests
{
    [Fact]
    public void BsonValue_ctorWithArray_AsArray_isvalid()
    {
        var strings = new string[] { "a", "b", "c" };
        var bsonValueOfArray = new BsonValue(strings);

        BsonArray instance = bsonValueOfArray.AsArray;
        Assert.NotNull(instance);
    }

}

ericnewton76 avatar Mar 20 '24 18:03 ericnewton76

Of note, trying to create a dotnetfiddle for showing it too: https://dotnetfiddle.net/dA5BLM

ericnewton76 avatar Mar 20 '24 18:03 ericnewton76

You are always welcome to issue a pr with the fix.

JKamsker avatar Jun 06 '24 04:06 JKamsker

I'm having the same issue and can't find a solution. After hours of troubleshooting it is clear that no matter how I try to add an array of strings (e.g., tags) to a BsonDocument and then insert it into a collection it fails because AsArray is always null. Can anyone else add an array of strings using a BsonDocument? Thank you.

payitforwardnow avatar Dec 27 '24 20:12 payitforwardnow