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,但显然这不是问题所在。
最佳答案
...it's like javascript is ignoring me assigning it.
这是完全可能的,如果分配对象是 sealed或 frozen由 MongoDB 提供。
相反,制作一个副本并将您的属性添加到副本中,也许使用 ES2018 的属性传播:
allocation = {...allocation, timestamp: moment(allocation.end_date).format('x')};
...或者如果您不能使用属性传播,Object.assign
:
allocation = Object.assign({}, allocation, {timestamp: moment(allocation.end_date).format('x')});
在这两种情况下,您都需要将 const
更改为 let
,因为我们正在更改变量 allocation
持有的值>。或者当然,将其保留为 const
并单独记住修改后的版本:
const updatedAllocation = {...allocation, timestamp: moment(allocation.end_date).format('x')};
response.status(200).send(updatedAllocation);
I've tried changing from const to let but apparently that's not the issue.
正确。 const
适用于变量(分配
),而不是变量引用的对象。
关于JavaScript 没有将元素分配给对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52425107/