我一直在阅读文档以及其他SO问题,但我真的找不到我做错了什么,即使在查看与我的代码几乎完全相同的问题时,提出的解决方案也没有用。
相关代码:
用户架构(身份验证使用它):
mongoose = require('mongoose')
Schema = mongoose.Schema
UserSchema = new Schema(
name:
type: String
required: true
password:
type: String
required: true
admin:
type: Boolean
default: false
apiKey:
type: String
required: true
)
User = mongoose.model('User', UserSchema)
module.exports = User
报告架构:
mongoose = require('mongoose')
Schema = mongoose.Schema
ReportSchema = new Schema(
# ...
votes: [{
user:
type: Schema.Types.ObjectId
ref: 'User'
text:
type: String
default: ''}]
# ...
)
Report = mongoose.model('Report', ReportSchema)
module.exports = Report
通过投票更新报告(req.user来自身份验证系统):
query =
_id: req.params.id
vote = req.body
params =
$push:
votes:
user: req.user._id
text: vote.text or ''
Report.findOneAndUpdate query, params, (err, result) ->
return res.status(500).send(err) if err
return res.status(404).end() unless result
res.send result
查看报告:
# ...
if (req.params.id)
Report.findOne({_id: req.params.id}).populate('votes.user').exec (err, report) ->
return res.status(404).end() unless report
res.send report
# ...
测试套件:
Report = mongoose.model "Report"
User = mongoose.model "User"
# ...
it "add a vote with a blank comment", (done) ->
Report.findOne title: 'test', (err, report) ->
return done(err) if err
request(app).put("#{apiUrl}/#{report._id}/vote").set("Authorization", "Bearer testKey").end (err, res) ->
return done(err) if err
expect(res.statusCode).toBe 200
Report.findOne title: 'test', (err, report) ->
console.log report
expect(report.votes?.length).toBe 1
expect(report.votes[0]?.text).toEqual ''
expect(report.votes[0]?.user?.name).toEqual 'test'
done()
在控制台中记录对象的内容:
报告(应填充投票数组中的用户字段):
{ _id: 5592d13e35c84be816000006,
...
__v: 0,
votes:
[ { user: 5592d14235c84be816000015,
_id: 5592d14335c84be816000017,
text: '' } ],
...
}
用户:
{ _id: 5592d14235c84be816000015,
apiKey: 'testKey',
password: 'testPassword',
name: 'test',
__v: 0,
admin: false }
如果有人可以帮我解决一些指导方针或指出错误,我会非常感激
提前谢谢你们!
答案 0 :(得分:0)
找到解决方案,这是一个简单的错误:我正在检查的报告是通过mongoose直接查找而不是通过我的API,这就是为什么它没有填充。正确的代码是:
Report.findOne title: 'test', (err, report) ->
return done(err) if err
request(app).put("#{apiUrl}/#{report._id}/vote").set("Authorization", "Bearer testKey").end (err, res) ->
return done(err) if err
expect(res.statusCode).toBe 200
request(app).get("#{apiUrl}/#{report._id}").set("Authorization", "Bearer testKey").end (err, res) ->
report = res.body
expect(report.votes?.length).toBe 1
expect(report.votes[0]?.texto).toEqual ''
expect(report.votos[0]?.user?.name).toEqual 'test'
done()
使用populate进行的API报告查找工作正常