ES6将两个变量组合成一个现有的javaScript对象
我当前正在返回数据对象外部的ES6将两个变量组合成一个现有的javaScript对象,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,我当前正在返回数据对象外部的createdAt和updatedAt,我想将它们添加到数据对象中,以便返回单个对象 我还注意到我从某处得到了$init:true,如何摆脱这个问题 static profile = async (req: Request, res: Response) => { try { const { username } = req.params; const account = await userModel .fi
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 });
}
};
static profile=async(请求:请求,响应:响应)=>{
试一试{
const{username}=req.params;
const account=await userModel
.findOne({'shared.username':username})
.exec();
如果(账户){
const{email,loggedIn,location,warningMessage,…data}=account.shared;
const{updatedAt,createdAt}=account;
物件
.现状(200)
.send({data,updatedAt,createdAt});//使用扩展运算符:
{…数据,更新数据,创建数据}
请注意,您的变量名将成为索引使用扩展运算符:
{…数据,更新数据,创建数据}
请注意,您的变量名将成为您的索引,以删除$init
,而不是其他内容
const {$init, ...cleanData} = data;
使用createdAt
和updatedAt
const finalData = {...cleanData, createdAt, updatedAt}
快乐编码!删除$init
,但不删除其他内容
const {$init, ...cleanData} = data;
使用createdAt
和updatedAt
const finalData = {...cleanData, createdAt, updatedAt}
愉快的编码!不要使用…data
rest模式,最好明确说明您在最终对象中到底想要什么属性,比如send({updatedAt:data.updatedAt,country:data.shared.country,…})
。您的意思是发送({data:{…data,updatedAt,createdAt})
?关于$init:true
我猜帐户是从mongo db检索的。IIRC您不应该直接以这种方式使用结果,但您需要使用toObject
const acc=account.toObject();const{email,loggedIn,location,…data}将其转换为普通对象=acc.shared;const{updatedAt,createdAt}=acc;
@Bill我猜它应该是这样的。我上次使用mongodb已经有很长时间了。与其使用…data
rest模式,不如明确说明您在最终对象中到底想要什么属性,比如send({updatedAt:data.updatedAt,country:data.shared.country,…})
。你的意思是.send({data:{…data,updatedAt,createdAt})
?关于$init:true
我猜帐户是从mongo db检索的。IIRC您不应该直接以这种方式使用结果,但您需要使用toObject
const acc=account.toObject();const{email,loggedIn,location,…data}将其转换为普通对象=acc.shared;常量{updatedAt,createdAt}=acc;
@我猜它应该是这样的。我上次使用mongodb已经有很长时间了。确实,你可以用这种方式去除$init
。但是如果它本来就不应该存在,那么正确的去除方法是找出它被添加的位置/原因,并确保它没有被添加。Ther我们已经发表了关于如何将Mongoose文档转换为POJO的评论。我认为最好为其他涉猎rest/spread.out的人添加有用的信息。确实,你可以用这种方式摆脱$init
。但是如果它本来就不应该存在,那么正确的方法就是摆脱它是为了弄清楚它是在哪里添加的/为什么添加的,并确保它没有被添加。已经有关于如何将Mongoose文档转换为POJO的评论。我认为最好为其他涉猎rest/spread的人添加有用的信息。