Skip to content Skip to sidebar Skip to footer

Mongodb - Mongoose - Typeerror: Save Is Not A Function

I am attempting to perform an update to a MongoDB document (using mongoose) by first using .findById to get the document, then updating the fields in that document with new values.

Solution 1:

You've now found a solution but I would suggest using the MongoDB driver which would make your code look something along the lines of this and would make the origional issue disappear:

// MongoDB SettingsconstMongoClient = require(`mongodb`).MongoClient;
const mongodb_uri = `mongodb+srv://${REPLACE_mongodb_username}:${REPLACE_mongodb_password}@url-here.gcp.mongodb.net/test`;
const db_name = `test`;
let db; // allows us to reuse the database connection once it is opened// Open MongoDB Connectionconst open_database_connection = async () => {
  try {
    client = awaitMongoClient.connect(mongodb_uri);
  } catch (err) { thrownewError(err); }
  db = client.db(db_name);
};


exports.updateData = async update => {

  // open database connection if it isn't already opentry {
    if (!db) awaitopen_database_connection();
  } catch (err) { thrownewError(err); }


  // update documentlet savedOutput;
  try {
    savedOutput = await db.collection(`testing`).updateOne( // .save() is being depreciated
      { // filter_id: update.id// the '_id' might need to be 'id' depending on how you have set your collection up, usually it is '_id'
      },
      $set: { // I've assumed that you are overwriting the fields you are updating hence the '$set' operator
        update // update here - this is assuming that the update object only contains fields that should be updated
      }

      // If you want to add a new document if the id isn't  found add the below line// ,{ upsert: true }

    );
  } catch (err) { thrownewError(`An error occurred while updating the Test document - ${err}`); }


  if (savedOutput.matchedCount !== 1) returnfalse; // if you add in '{ upsert: true }' above, then remove this line as it will create a new documentreturn savedOutput;
}

The collection testing would need to be created before this code but this is only a one-time thing and is very easy - if you are using MongoDB Atlas then you can use MongoDB Compass / go in your online admin to create the collection without a single line of code...

As far as I can see you should need to duplicate the update object. The above reduces the database calls from 2 to one and allows you to reuse the database connection, potentially anywhere else in the application which would help to speed things up. Also don't store your MongoDB credentials directly in the code.

Post a Comment for "Mongodb - Mongoose - Typeerror: Save Is Not A Function"