尝试测试架构时出现以下错误:
“CastError:施放到ObjectId失败的值”{by:58803a77479f7e2a2d069d93,at:2017-01-19T04:03:03.156Z}“at path”_id“for model”Poll“
const PollSchema = Schema({
title: {
type: String,
required: true
},
desc: {
type: String
},
created : {
by: {
type: Schema.Types.ObjectId,
ref: 'User'
},
at: {
type: Date,
default: Date.now
}
}
})
这是测试代码
describe('Associations', () => {
let _cindy, _poll;
beforeEach((done) => {
_cindy = new User ({
firstName : 'Cindy',
lastName : 'Cronkite'
})
_poll = new Poll ({
title : 'my first blog',
desc : 'yada yada yada'
created : {
by : _cindy._id
}
})
_poll.created = _cindy
_cindy.save()
.then(() => {
_poll.save().then(() => done())
})
})
it('saves a relation between a user and a poll', (done) => {
Poll.findOne({ title : 'my first blog'})
.populate('created')
.then( (_pollQuery) => {
console.log('_pollQuery', _pollQuery)
assert(_pollQuery.created.by.firstName === 'Cindy')
done()
})
})
})
答案 0 :(得分:1)
您需要填充created.by
Poll.findOne({ title : 'my first blog'})
.populate('created.by')
我建议使用populate
聚合而不是$lookup
,以便在单个查询中提取数据。