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
})
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.
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.
find returns an array always.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With