litedb-org/LiteDB · error · LiteException

0

0

Error message

Collection ${this.Name} requires string as 'filename' or a document field 'filename'

What it means

Thrown by SysFileJson.Input when reading JSON from $file_json and the 'filename' option is missing or not a string. Uses ${this.Name} so the message correctly shows $file_json. Occurs before the FileStream/JsonReader are opened.

Source

Thrown at LiteDB/Engine/SystemCollections/SysFileJson.cs:18

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using static LiteDB.Constants;

namespace LiteDB.Engine
{
    internal class SysFileJson : SystemCollection
    {
        public SysFileJson() : base("$file_json")
        {
        }

        public override IEnumerable<BsonDocument> Input(BsonValue options)
        {
            var filename = GetOption(options, "filename")?.AsString ?? throw new LiteException(0, $"Collection ${this.Name} requires string as 'filename' or a document field 'filename'");
            var encoding = GetOption(options, "encoding", "utf-8").AsString;

            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var reader = new StreamReader(fs, Encoding.GetEncoding(encoding)))
                {
                    var json = new JsonReader(reader);

                    var source = json.DeserializeArray()
                        .Select(x => x.AsDocument);

                    // read documents inside file and return one-by-one
                    foreach (var doc in source)
                    {
                        yield return doc;
                    }
                }
            }

View on GitHub (pinned to f906a5f850)

Solutions

  1. Pass the filename: $file_json('data.json') or { filename: 'data.json' }.
  2. Prefer $file('data.json') for extension-based routing.
  3. Validate the filename option is a string before executing.

Example fix

// before
db.Execute("SELECT * FROM $file_json()"); // throws

// after
db.Execute("SELECT * FROM $file_json('data.json')");
Defensive patterns

Strategy: validation

Validate before calling

if (string.IsNullOrWhiteSpace(filename)) throw new ArgumentException("filename required");
db.Execute($"SELECT * FROM $file_json('{filename}')");

Try / catch

try { db.Execute($"SELECT * FROM $file_json('{filename}')"); }
catch (LiteException ex) when (ex.Message.Contains("requires string as 'filename'")) {
    // obtain filename and retry
}

Prevention

When it happens

Trigger: SELECT * FROM $file_json() with no filename, or $file_json({ encoding:'utf-8' }) without filename, or filename as a non-string.

Common situations: Using $file_json directly and omitting the filename; building options dynamically without the filename key.

Related errors


AI-assisted analysis of litedb-org/LiteDB@f906a5f850 (2026-08-13). Data as JSON: /api/errors/4f11291c4c37990e. Report an issue: GitHub.