Vpp Man
Vpp Man

Reputation: 2546

Mongoose - Update same record after insert

I am inserting a new record like this(Book is the model):

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

Here, instead of using findOneAndUpdate() to update the file_name field, is there a better approach like doing it in a single shot?

Upvotes: 0

Views: 81

Answers (2)

Smriti Shikha
Smriti Shikha

Reputation: 431

you can try this

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();

Upvotes: 2

sahil khaire
sahil khaire

Reputation: 79

Below code might help you.

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();

Upvotes: 0

Related Questions