首页 > 解决方案 > 如何在单个插入中在文档的其他字段中使用生成的 id

问题描述

我需要创建一个文件,其名称为(“[document_id].png”)。但是数据库文档必须包含文件路径,所以基本上我在做什么:

insertFileDatabase() //saves database document without file path and return inserted id
createFile() //create file with the inserted id and return file path
updateFileDatabase() //updates database document file inserting the file path

有没有一种方法可以在不需要更新文档的情况下做到这一点?避免发出两个数据库请求。

标签: mongodbgo

解决方案


使用MongoDB Go 驱动程序,您可以先创建 ID,然后使用它来插入。例如:

  myId := primitive.NewObjectID()

  myPath, _ := createFile(myId) // create a file with the generated id and return file path 

  insertFileDatabase(myId, myPath) // insert into database a document with file path and id. 

请注意,这_id将采用ObjectId的形式。ObjectId 很小,可能是唯一的,生成速度快,并且是有序的。ObjectId 值的长度为 12 个字节。

有关更多信息,请参阅primitive.NewObjectID


推荐阅读