首页 文章

为什么我会为以下mongooseJS架构收到转换错误?

提问于
浏览
0

尝试测试架构时出现以下错误:

“CastError:Cast to ObjectId for value”{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()
        })
})
})

1 回答

  • 1

    你需要填充 created.by

    Poll.findOne({ title : 'my first blog'})
            .populate('created.by')
    

    而不是 populate ,我建议使用 $lookup 聚合,以便在单个查询中获取数据 .

相关问题