-1

I am using "mongodb": "^3.1.6",.

I have a method using the drivers insertOne method (shops is my mongoDb database collection):

/**
   * Adds a new shop to the shops collection
   * @param {Shop} doc - the new shop to add
   */
  static async addShop(shop) {
    try {
      return await shops.insertOne(shop, {}, (err, result) => {
        if (err) {
          throw e
        }
        return result
      })
      // TODO this should return the new shop
    } catch (e) {
      console.error(`Something went wrong in addShop : ${e}`)
      throw e
    }
  }

Now the method inserts the document into the collection as expected, but does not return the insert result. How do I return the result value of the callback function?

For reference - I wrote this unit test that I want to get to pass:

test("addShop returns the added shop", async () => {
    const testShop = {
      name: "Test shop for jest unit tests",
    }
    const newShop = await ShopsDAO.addShop(testShop)
    const shoppingCart = global.DBClient.db(process.env.NS)
    const collection = shoppingCart.collection("shops")
    expect(newShop.name).toEqual(testShop.name)
    await collection.remove({ name: testShop.name })
  })

Thanks for the help.

Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163
  • `insertOne` should return the id of the newly created document: https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/. You can subsequently use `findOne` to retrieve the created document: https://docs.mongodb.com/manual/reference/method/db.collection.findOne/. – t.888 Jun 24 '19 at 21:09

1 Answers1

-1

I suggest you not to mix promises and callbacks as it is a bad way to organize your code. According to docs, if you do not pass callback insertOne will return Promise. So I suggest you to rewrite function smth like that:

  static async addShop(shop) {
    try {
      return shops.insertOne(shop)
    } catch (insertError) {
      console.error(`Something went wrong in addShop : ${insertError}`)
      throw insertError
    }
  }

This addShop will return promise, use await to retrieve data from it:

const newShop = await ShopsDAO.addShop(testShop)

P.S. You can also omit await with return statement

V.Panichkin
  • 27
  • 1
  • 5
  • 1
    This returns an object with the new inserted document _id. As suggested in the comment above I had to use `findOne` to retrieve and return the new document. – Miha Šušteršič Jun 25 '19 at 07:29