Mongoose - 插入后更新相同的记录

分享于2022年07月17日 database mongodb mongoose node.js 问答
【问题标题】:Mongoose - 插入后更新相同的记录(Mongoose - Update same record after insert)
【发布时间】:2022-01-26 10:40:30
【问题描述】:

我正在插入这样的新记录( Book 是模型):

var ext = 'pdf'

var dataToInsert = {
  'author': 'ABC',
  'country': 'US',
  'file_name': ''
}

var new_book = new Book( dataToInsert );
await new_book.save();

const file_name = new_book._id + '.' + ext

//-- update the document with the new file_name

在这里,不是使用 findOneAndUpdate() 来更新 file_name 字段,有没有更好的方法,比如一次性完成?


【解决方案1】:

你可以试试这个

var ext = 'pdf'

var dataToInsert = {
  'author': 'ABC',
  'country': 'US',
  'file_name': ''
}

var new_book = new Book( dataToInsert );

// create mongo id before saving and use that id for file_name creation
new_book._id = mongoose.Types.ObjectId()

new_book.file_name = new_book._id + '.' + ext

await new_book.save();