我有这段代码:
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((
这奏效了:
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
}
}