简体   繁体   English

没有使用Array.Map()更新Javascript对象

[英]Javascript object not updating with Array.Map()

I have an Express API in which I have the following Mongoose query that extracts posts from the database and then I want to convert the timestamp from the database (a Date() object) into a relative time string. 我有一个Express API,其中我有以下Mongoose查询从数据库中提取帖子然后我想将时间戳从数据库(Date()对象)转换为相对时间字符串。

As you can see, I am trying to add a time property that has this string as a value to the posts object using Array.Map. 如您所见,我正在尝试使用Array.Map添加一个time属性,该属性将此字符串作为值添加到posts对象。

That seems to work, because logging items[0].time in the console returns the proper value (see comment in the cose). 这似乎有效,因为在控制台中记录items[0].time返回正确的值(请参阅cose中的注释)。

HOWEVER! 然而! when sending the object back with res.json, the time property is not in it. 当使用res.json发回对象时, time属性不在其中。

I thought this might be a client-side cache issue, but when adding another value in res.json , the new value gets sent along with the posts just fine. 我认为这可能是客户端缓存问题,但是当在res.json添加另一个值时,新值与帖子一起发送就好了。

Post.find({}, 'author text timestamp')
        .sort({ _id: -1 })
        .populate({ path: 'author', select: 'username' })
        .exec(function(error, posts) {
          if (error) {
            console.error(error)
          }


          items = posts.map(function(item) {
            item.time = moment(item.timestamp).fromNow()
            return item
          })

          console.log('Relative date:' + items[0].time) // This logs: "Relative date:an hour ago"

          res.json({
            posts: items
          })
          /*
            Response:

            posts: {
              0: {
                author: {_id: "5c98f40f793edf61bcc94b4d", username: "Admin"},
                text: "Why",
                timestamp: "2019-04-04T15:46:36.142Z",
                _id: "5ca626dc45734a2612acbcd2"
              }
            }
          */
        })

Is this a server-related cache issue or something unique to Mongoose objects that I don't know about? 这是与服务器相关的缓存问题还是我不​​知道的Mongoose对象的独特之处?

Thanks in advance for the help. 先谢谢您的帮助。

我能够在我的代码中使用Post.find()。lean()来解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM