【问题标题】:Missing property at client side Nodejs客户端Nodejs缺少属性
【发布时间】:2018-09-09 13:39:26
【问题描述】:

我的简单问题是:

我在服务器端有一个猫鼬对象:

... item = { name: "Test", id: 1 }

// item 是一个 mongo 模式

// id 和 name 在模型 StringNumber 中定义

然后我添加到item 新字段mentions

item.mention = [{ id: 1, ... }]

但我无法在客户端获得mention

我的回复码:

res,json({ status: 1, message: 'success', data: item })

回复是data: { name: "Test", id: 1 }

我不想将 mention 添加到我的 mongo 架构中。

那么,我的问题是什么?

我该如何解决这个问题?

谢谢!

【问题讨论】:

    标签: node.js object mongoose server


    【解决方案1】:

    利用Object.assign() 也应该可以解决您的问题。

    res.json({
        status: 1,
        message: 'success',
        data: Object.assign({ mention: [{id: 1...}] },item)
    })
    

    【讨论】:

      【解决方案2】:

      问题在于itemMongooseDocument,而不是普通的javascript 对象。

      有多种方法可以实现您想要的。

      1) 使用.lean()

      启用了精简选项的查询返回的文档是普通的 javascript 对象,而不是 MongooseDocuments

      Model.findOne().lean().exec((err, item) => {
          item.mention = [{ id: 1 }];
          res.json(item);
      });
      

      此选项将提高性能,因为您忽略了创建 Mongoose 文档的开销

      2) 使用:.set()

      item.set('mention', [{ id: 1}], { strict: false });
      

      4) 使用spread operator

      res.json({
          status: 1,
          message: 'success',
          data: { mention: [{ id: 5 }], ...item }
      })
      

      4) 使用Object.assign @Alexis Facques 解释。

      【讨论】:

        猜你喜欢
        • 2018-06-29
        • 2021-11-08
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多