【问题标题】:Populating after saving保存后填充
【发布时间】:2019-07-04 00:31:36
【问题描述】:

我有这段代码:

message.save().then(message => {
    let result = {
        ok: true,
        message
    }
    res.send(result);
})

这给出了这个 json:

{
    "ok": true,
    "message": {
        "_id": "5c5fe65236bcc31eb0a3db46",
        "from": "5c5f1f1c4042b431d4611127",
        "to": "5c5f201b4042b431d4611128",
        "message": "Con imagen",
        "image": "img/1549788754143.jpg",
        "sent": "2019-02-10T08:52:34.144Z",
        "__v": 0
    }
}

我想填充 from 字段,这是最好的方法吗? 我只在 .find() 之后使用了填充,我找不到任何方法。

.save() 不允许你使用 .populate()

【问题讨论】:

    标签: node.js json web-services express mongoose


    【解决方案1】:

    这行得通:

    message.save().then(savedMessage => {
                Message.findById(savedMessage._id).populate('from').then(data => {
                    let result = {
                        ok: true,
                        data
                    }
                    res.send(result);
                })
            })
    

    .save() 没有 .populate() 方法,因此这个技巧可以在 Web 服务中返回填充字段,这非常有用。

    这个 web 服务返回的 json 现在是这样的:

    {
        "ok": true,
        "data": {
            "_id": "5c60791c834b900bf0383440",
            "from": {
                "_id": "5c5f1f1c4042b431d4611127",
                "name": "admin",
                "password": "03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4",
                "image": "img/1549737756964.jpg",
                "__v": 0
            },
            "to": "5c5f201b4042b431d4611128",
            "message": "Con imagen",
            "image": "img/1549826332017.jpg",
            "sent": "2019-02-10T19:18:52.018Z",
            "__v": 0
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2012-11-11
      • 2021-11-17
      • 2017-12-16
      • 1970-01-01
      • 2019-12-29
      • 2014-09-06
      • 1970-01-01
      • 2016-06-10
      相关资源
      最近更新 更多