我有一个包含bellow的对象的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"
}
Note :也有一些嵌套字段,例如UserId。
试图使用批量插入错误插入错误
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/string?例如ObjectId("5d1de1bab90f8bf15f58df3f")
或"5d1de1bab90f8bf15f58df3f"
DB中的预期输出:
{
userID: ObjectId("5d1de1bab90f8bf15f58df3f"),
userName: "abc"
}
或
{
userID: "5d1de1bab90f8bf15f58df3f",
userName: "abc"
}
谢谢你,
您已经让我走上了正确的轨道。只是为了它。这是我的效用功能。冗长但有效。
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
}
我在objectid插入的情况下也能够解决。这些步骤 - 尽管看来是在这种情况下 - 将实现目标:
1 。将base10 int数组的ID转换为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();