I'm currently returning createdAt
and updatedAt
outside of the data object, I want to add them to the data object so I can return a single object.
I've also noticed I'm getting $init: true
from somewhere, how to get rid of this?
static profile = async (req: Request, res: Response) => {
try {
const { username } = req.params;
const account = await userModel
.findOne({ 'shared.username': username })
.exec();
if (account) {
const {email, loggedIn, location, warningMessage, ...data} = account.shared;
const { updatedAt, createdAt } = account;
res
.status(200)
.send({ data, updatedAt, createdAt }); // <=== How to combine updatedAt & createdAt into data?
} else res.status(400).send({ message: 'Server Error' });
} catch (error) {
res.status(400).send({ message: 'Server Error', error });
}
};
The current result is
createdAt: "2019-12-13T12:15:05.031Z"
data: {
$init: true // <=== why is this here, where did it come from?
avatarId: "338fcdd84627317fa66aa6738346232781fd3c4b.jpg"
country: "AS"
fullName: "Bill"
gender: "male"
language: "en"
username: "bill"
}
updatedAt: "2019-12-14T16:07:34.923Z"
Use spread operator:
{ ...data, updatedAt, createdAt }
Be warning, your variable name gonna be your index
To remove $init
but nothing else.
const {$init, ...cleanData} = data;
To create a data object with createdAt
and updatedAt
const finalData = {...cleanData, createdAt, updatedAt}
Happy coding!
Just use .toObject() like so:
static profile = async (req: Request, res: Response) => {
try {
const { username } = req.params;
const _account = await userModel
.findOne({ 'shared.username': username })
.exec();
const account = _account.toObject()
if (account) {
const {email, loggedIn, location, warningMessage, ...data} = account.shared;
const { updatedAt, createdAt } = account;
res
.status(200)
.send({ data: { ...data, ...{ updatedAt, createdAt }} });
} else res.status(400).send({ message: 'Server Error' });
} catch (error) {
res.status(400).send({ message: 'Server Error', error });
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.