保存后填充

时间:2019-02-10 09:01:43

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

我有这段代码:

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
    }
}

我要填充发件人字段,这是最好的方法? 我只在.find()之后使用填充,但找不到任何方法。

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

1 个答案:

答案 0 :(得分:0)

这有效:

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
    }
}