如何使用node.js将_bsontype objectID值转换为要插入到mongoDB中的字符串/ objectID

时间:2019-07-04 13:02:44

标签: javascript node.js mongodb objectid

我有一个包含以下对象的JSON文件。

{
    userID: {"_bsontype":"ObjectID","id":{"0":92,"1":237,"2":216,"3":42,"4":254,"5":178,"6":68,"7":182,"8":208,"9":254,"10":51,"11":64}},
    userName: "abc"
}

注意:还具有一些嵌套字段,例如userID。

当尝试使用批量插入导入MongoDB时出现错误

UnhandledPromiseRejectionWarning: Error: object [{"_bsontype":"ObjectID","id":{"0":92,"1":237,"2":216,"3":42,"4":254,"5":178,"6":68,"7":182,"8":208,"9":254,"10":51,"11":64}}] is not a valid ObjectId

如何将userID转换为objectID /字符串?像ObjectId("5d1de1bab90f8bf15f58df3f")"5d1de1bab90f8bf15f58df3f"

数据库中的预期输出:

{
    userID: ObjectId("5d1de1bab90f8bf15f58df3f"),
    userName: "abc"
}

{
    userID: "5d1de1bab90f8bf15f58df3f",
    userName: "abc"
}

2 个答案:

答案 0 :(得分:2)

谢谢你,

您已使我走上正轨。只是为了它。这是我的效用函数。详细,但有效。

const { ObjectID } = require( 'mongodb' )

  toObjectID: function ( object ) {
    let hexString = ''
    Object.values(object.id).forEach(elem =>{
      const result = elem.toString(16)
      if(result.length === 2) {
        hexString += result
      } else {
        hexString += "0" + result
      }
    })
    const id = new ObjectID(hexString)
    return id
  }

答案 1 :(得分:0)

我可以解决与ObjectID插入类似的情况。这些步骤-尽管看起来似乎是针对情况的,但可以实现目标:

1 。将id从base10 int数组转换为base16个字符的字符串:

const idString = obj.userID.id.map(num => {
  var result = num.toString(16);
  return result.length == 2 ? num : "0" + num;
})
.join('');

2 。从字符串创建对象ID:

const _id = ObjectID(idString);

3 。转换回字符串 从ObjectID转换回mongodb在插入或更新文档时期望的ObjectID()形式:

_id.toString();