JavaScript 没有将元素分配给对象

标签 javascript mongodb mongoose async-await

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.

这是完全可能的,如果分配对象是 sealedfrozen由 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/

相关文章:

javascript - 将网页中的字符串与 HTML 标记匹配

javascript - 为图表融合渲染容器设置圆 Angular

mongodb - 将带有日期的文档插入到 Robomongo 的集合中

java - Spring Data Mongodb 的性能问题

node.js - 如何使用带有 postgres 的 sequelize 定义与具有外键数组的模型的关联

node.js - 如何在node.js中隐藏 Mongoose 连接信息?

javascript - 如何在 WebStorm 中指定特定的 tsconfig.json

javascript - 使用javascript在网页中 append 重复图像

javascript - 在 Node 中发布请求时从mongo获取数据?

node.js - 更新双重嵌套数组 MongoDB