【发布时间】:2019-12-14 16:23:02
【问题描述】:
我目前在数据对象之外返回createdAt 和updatedAt,我想将它们添加到数据对象中,以便我可以返回单个对象。
我还注意到我从某个地方收到了$init: true,如何摆脱它?
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 });
}
};
当前结果是
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"
【问题讨论】:
-
与其使用
...data休息模式,不如明确说明您想要在最终对象中的哪些属性,例如send({ updatedAt: data.updatedAt, country: data.shared.country, … })。 -
你的意思是
.send({data: {...data, updatedAt, createdAt }})? -
关于
$init: true我猜account是从mongo db 中检索到的。 IIRC,您不应该直接使用结果,但您需要使用toObject将其转换为普通对象。 -
const acc = account.toObject(); const { email, loggedIn, location, ...data } = acc.shared; const { updatedAt, createdAt } = acc; -
@Bill 我猜它应该是这样的。上次用mongodb已经很久了。
标签: javascript node.js ecmascript-6