Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the return of a created object in Mongoose with express api

In my express api, using mongoose, i create a new user on api using User.create. How i can get the return of the created object to include on the response?

My method to create a object is:

async store (req, res) {
const { name, lastName, email, password } = req.body

if (await User.findOne({ email })) {
  return res.status(400).json({ error: 'User already exists' })
}

try {
  await User.create({
    name,
    lastName,
    email,
    password,
    role: 'USER_ROLE'
  })

  res.status(201).json({
    ok: true,
    message: 'User created'
  })
} catch (e) {
  res.status(500).json({
    ok: false,
    message: 'Failed to create User'
  })
}

}

I want to return the user created on the res, like:

 res.status(201).json({
    ok: true,
    message: 'User created',
    user: user

  })
like image 733
Fábio Jansen Avatar asked Jan 10 '19 09:01

Fábio Jansen


People also ask

What does Mongoose find return?

find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries. You don't instantiate a Query directly, Customer.

Does Mongoose save return a promise?

While save() returns a promise, functions like Mongoose's find() return a Mongoose Query . Mongoose queries are thenables. In other words, queries have a then() function that behaves similarly to the Promise then() function. So you can use queries with promise chaining and async/await.

Does find return an array Mongoose?

find returns an array always.

What is update return Mongoose?

By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied. Mongoose's findOneAndUpdate() is slightly different from the MongoDB Node.


1 Answers

async store(req, res) {
  const { name, lastName, email, password } = req.body

  if (await User.findOne({ email })) {
    return res.status(400).json({ error: 'User already exists' })
  }

  try {
    let user = await User.create({
      name,
      lastName,
      email,
      password,
      role: 'USER_ROLE'
    })
    user = user.toJson();
    delete user.password;
    delete user.role;
    res.status(201).json({
      ok: true,
      user: user,
      message: 'User created'
    })
  } catch (e) {
    res.status(500).json({
      ok: false,
      message: 'Failed to create User'
    })
  }
}

You can covert mongoose object to JSON using

user.toJson()

Then you can delete the fields that you don't want to send into the response.

delete user.password;
like image 64
Niral Munjariya Avatar answered Oct 13 '22 01:10

Niral Munjariya