Home > Enterprise >  Mongoose - Update same record after insert
Mongoose - Update same record after insert

Time:12-27

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?

CodePudding user response:

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

CodePudding user response:

I think this might help you. When you are creating the _id, it should be an incremental one rather than a random one. If this is the case, you can keep the counter for the last one and when you save the book append the filename by incrementing the last id.

This way you don't need to make the update call. I am not sure when you save a lot of data ex may be more than 100k, how the _id will be incrementing. This is how the _id field is created by mongodb.

  1. a 4-byte value representing the seconds since the Unix epoch,

  2. a 3-byte machine identifier,

  3. a 2-byte process id, and a 3-byte counter, starting with a random value."

Or, you can create your own unique id and keep it in the environment variables and increment it.

CodePudding user response:

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