【问题标题】:Failed to parse: comment: 1. \'comment\' field must be of BSON type string解析失败:comment: 1. \'comment\' 字段必须是 BSON 类型字符串
【发布时间】:2017-10-30 13:08:36
【问题描述】:

我正在使用 mongodb 本机驱动来获取查询结果的光标。 我正在使用一个“评论”字段,它基本上是一个字符串,下面是代码 sn-p 我正在使用

let leve1_n = 'labreports';
let matchLabReports = { level1_n: "labreports" };
let sortCondition = { _id: 1 };
let projection = {comment : 1 , color: 1, value: 1, value_n: 1, value_d: 1, rangeStart: 1, rangeEnd: 1, level2: 1 };
let collectionName = collectionNames.biomarkerAggregations;
let cursor = dbModule.findCursorSort(dbModule.getDbHandle(dbName), collectionName, matchLabReports, projection,sortCondition);

        cursor.forEach(doc => {    
        // Lambda Expression
        // Do something with doc.
        })

findcursorSort

function findCursorSort(db, collectionName, query, projection, sortCondition, options) {
    if (!errorCheck(db)) {
        let cursor = db.collection(collectionName).find(query, projection).sort(sortCondition);
        if (!options) {
            return cursor;
        }
        for (let i = 0; i < options.length; i++) {
            cursor = cursor.addOption(options[i]);
        }
        return cursor;
    }
}

但这给了我类似的错误..

名称:'MongoError', message: '解析失败:comment: 1. \'comment\' 字段必须是 BSON 类型的字符串。', 好的:0, errmsg: '解析失败: 注释: 1. \'comment\' 字段必须是 BSON 类型的字符串。', 代码:9, 代号:'FailedToParse' }

从项目中删除评论字段后,一切正常。 任何帮助将不胜感激。

【问题讨论】:

  • .findCursorSort() 是您代码中的自定义函数。它有什么作用?我们需要知道,因为错误来自该函数“内部”的代码。
  • 不相关(我认为),但我也猜测这个let leve1_n = 'labreports'; let matchLabReports = { level1_n: "labreports" }; 实际上是指let leve1_n = 'labreports'; let matchLabReports = { }; matchLabReports[level1_n] = "labreports";,这实际上是您为查询分配动态键的方式。您的代码将被字符串化为{ "level1_n": "labreports" },尽管您可能认为您正在使用变量值。你不是,因为这不是 JavaScript 对象中键名的工作方式。
  • @NeilLunn 感谢您的热情回复。是的 .findCursorSort() 是一个自定义函数,这里是这个函数的代码。 jsfiddle.net/jjv0g6k0
  • 请不要尝试在 cmets 中粘贴代码。您问题上的Edit 链接用于添加详细信息。

标签: javascript node.js mongodb typescript


【解决方案1】:

在mongodb原生驱动的collection.js中有一个特性,可以检查哪些字段是查询的选项,哪些是投影。如果投影中的所有字段都包含一些字段,如评论、限制、排序等(写在 testForFields 变量中),则它们将作为选项。

尝试像这样解决这个问题:

原代码:

db.collection(collectionName).find(query, projection)

固定代码:

db.collection(collectionName).find(query).project(projection)

它帮助我解决了问题。

【讨论】:

    猜你喜欢
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    相关资源
    最近更新 更多