qwang07
qwang07

Reputation: 1256

How did mongoose decide to 'insert' or 'update' an document when call document.save()?

I moving from MongoDB to Postgres. But I still prefer some interface that provides by the mongoose. Thus I try to implement them. Here is the problem, I create a class called 'User'. It has 'save' method. In mongoose, no matter when I update or create a new document, I can call 'save' to insert/update the document into the database. How did they implement it? any suggestions?

Here is what I tried, but I'm not sure is that a good practice or not:

class User {
  constructor (obj) {
    for (let key in obj) {
      this[key] = obj[key]
    }

    Object.defineProperty(newAdmin, 'exist', {
      configurable: true,
      writable: true,
      enumerable: false,
      value: false
    })
  }

  async update () {//}

  async save () {
    const user = this
    if (user.exist) {
      return user.update()
    }
    const query = `query here`
    const {rows} = await db.query(query)
    Object.assign(user, rows[0])
    user.exist = true
    return user
  }
}

Upvotes: 0

Views: 152

Answers (1)

Martin Campbell
Martin Campbell

Reputation: 1798

MongoDB supports the concept of upsert when updating a document. How mongoose updates the DB from your models depends on the exact method you use. However, it was likely using the functionality.

This is now present in postgres 9.5+, see the UPSERT documentation.

In short, you can do run an INSERT statement and using ON CONFLICT UPDATE, force it to update columns when a constraint error occurs (e.g. row already present for primary key).

For example, you could do something like:

INSERT INTO users (ID,Name) VALUES(1,'john')
ON CONFLICT ON CONSTRAINT users_pkey DO
UPDATE SET Name=EXCLUDED.Name

Upvotes: 1

Related Questions