【问题标题】:Mongoose - Update same record after insertMongoose - 插入后更新相同的记录
【发布时间】: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 字段,有没有更好的方法,比如一次性完成?
【问题讨论】:
标签:
node.js
database
mongodb
mongoose
【解决方案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();
【解决方案2】:
以下代码可能会对您有所帮助。
const ext = 'pdf'
const dataToInsert = {
'author': 'ABC',
'country': 'US',
'file_name': ''
}
const new_book = new Book( dataToInsert );
await new_book.save();
new_book.file_name = new_book._id + '.' + ext;
new_book.save();