最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

将 JSON 加载到 mongoose 文档时解析 `$oid`

网站源码admin36浏览0评论

将 JSON 加载到 mongoose 文档时解析 `$oid`

将 JSON 加载到 mongoose 文档时解析 `$oid`

我正在为我的后端编写测试。我正在使用

mongoose
.

为了避免从我的数据库中编写一个巨大的示例文档作为模拟,我将该文档复制粘贴到一个 JSON 文件中。

转储文档将

ObjectId
s转换为:

"_id": {
  "$oid": "6457a66965cfa04f2c2bf00f",
}

如果我将其加载到文档中,那么我的

_id
字段将只是通用对象,而不是
mongoose.Types.ObjectId

我也试过用我的模型加载它

const Model = mongoose.model("MyModel", schema);
export const document = new Model(
{
 "_id": {
  "$oid": "6457a66965cfa04f2c2bf00f"
 }
});

但我得到了相同的结果。

我怎样才能让

mongoose
解析
$oid

回答如下:
"_id": {
  "$oid": "6457a66965cfa04f2c2bf00f",
}

Canonical Modemongodb-extended-json

的JSON格式

我猜你从 cloud mongodb 复制文档如下:

复制文件示例:

{ "_id": { "$oid": "6453682c4fd3563f4b9ccb0a" }, "username": "teresa teng", "email": "[email protected]", "password": "123456", "notes": [{ "_id": { "$oid": "6453682c4fd3563f4b9ccb0c" }, "title": "b", "text": "b-text", "createdAt": { "$date": { "$numberLong": "1683187756818" } }, "updatedAt": { "$date": { "$numberLong": "1683187756818" } } }], "createdAt": { "$date": { "$numberLong": "1683187756819" } }, "updatedAt": { "$date": { "$numberLong": "1683188038452" } }, "__v": { "$numberInt": "1" } }

现在,让我们从云 Mongodb 中删除这个用户文档,并使用上面的 mongodb 扩展 JSON 重新创建它。我将使用 bson 包的

EJSON.parse(text, [options])

解析扩展 JSON 字符串,构造该字符串描述的 JavaScript 值或对象。

当我们得到解析后的js对象,我们就可以用它来创建我们的用户文档了

例如

const copiedDocument = { "_id": { "$oid": "6453682c4fd3563f4b9ccb0a" }, "username": "teresa teng", "email": "[email protected]", "password": "123456", "notes": [{ "_id": { "$oid": "6453682c4fd3563f4b9ccb0c" }, "title": "b", "text": "b-text", "createdAt": { "$date": { "$numberLong": "1683187756818" } }, "updatedAt": { "$date": { "$numberLong": "1683187756818" } } }], "createdAt": { "$date": { "$numberLong": "1683187756819" } }, "updatedAt": { "$date": { "$numberLong": "1683188038452" } }, "__v": { "$numberInt": "1" } };
const obj = bson.EJSON.parse(JSON.stringify(copiedDocument));
console.log('obj: ', obj);
const user = new UserModel(obj)
await user.save();

执行结果:

obj:  {
  _id: new ObjectId("6453682c4fd3563f4b9ccb0a"),
  username: 'teresa teng',
  email: '[email protected]',
  password: '123456',
  notes: [
    {
      _id: new ObjectId("6453682c4fd3563f4b9ccb0c"),
      title: 'b',
      text: 'b-text',
      createdAt: 2023-05-04T08:09:16.818Z,
      updatedAt: 2023-05-04T08:09:16.818Z
    }
  ],
  createdAt: 2023-05-04T08:09:16.819Z,
  updatedAt: 2023-05-04T08:13:58.452Z,
  __v: 1
}

已成功重新创建用户文档。

发布评论

评论列表(0)

  1. 暂无评论