JavaScript没有为对象分配元素 [英] JavaScript not assigning an element to the object

查看:73
本文介绍了JavaScript没有为对象分配元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const allocation_me = async (request, response) => {
  try {
    const { user: userid } = request;
    if (!ObjectId.isValid(userid)) throw new Error('invalid objectid');

    const now = moment().format();
    const date = new Date(now);
    const allocation = await Allocation.findOne({ $and: [{ user: userid, start_date: { $lt: date }, end_date: { $gt: date } }] })
      .populate('user', 'name')
      .populate('garden');
    if (!allocation) throw new Error('invalid request');
    allocation.timestamp = moment(allocation.end_date).format('x');
    response.status(200).send(allocation);
  } catch (error) {
    response.status(400).send(error);
  }
};

我正在尝试将时间戳添加到mongo查询返回的对象,但是当它发送分配作为响应时,时间戳不会显示.我已经尝试记录了allocation.timestamp值,但它也不显示,就像javascript忽略了我分配它一样.我尝试将const更改为let,但是显然这不是问题.

I'm trying to add the timestamp to the object that is returned by the mongo query but when it sends the allocation as the response, the timestamp doesn't show up. I've tried to log the allocation.timestamp value and it doesn't show either, it's like javascript is ignoring me assigning it. I've tried changing from const to let but apparently that's not the issue.

推荐答案

...这就像javascript忽略了我分配它一样.

...it's like javascript is ignoring me assigning it.

如果分配对象是冻结,由MongoDB提供.

That's entirely possible, if the allocation object is sealed or frozen by MongoDB.

相反,制作副本并将您的媒体资源添加到副本中,也许会传播ES2018的媒体资源:

Instead, make a copy and add your property to the copy, perhaps with ES2018's property spread:

allocation = {...allocation, timestamp: moment(allocation.end_date).format('x')};

...或者如果您不能使用属性传播,请Object.assign:

...or if you can't use property spread, Object.assign:

allocation = Object.assign({}, allocation, {timestamp: moment(allocation.end_date).format('x')});

在这两种情况下,都需要将const更改为let,因为我们要更改变量allocation持有的值.或者,当然,将其保留为const并分别记住修改后的版本:

You'll need to change const to let in both of those cases, since we're changing the value held by the variable allocation. Or of course, leave it as a const and remember the modified version separately:

const updatedAllocation = {...allocation, timestamp: moment(allocation.end_date).format('x')};
response.status(200).send(updatedAllocation);


我尝试将const更改为let,但这显然不是问题所在.

I've tried changing from const to let but apparently that's not the issue.

正确. const适用于变量(allocation),而不适用于变量所引用的对象.

Correct. const applies to the variable (allocation), not the object the variable refers to.

这篇关于JavaScript没有为对象分配元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆