Mongoose CastError: Cast to embedded failed for value

問題描述

最近使用mongoose遇到個錯誤CastError: Cast to embedded failed for value,搜了一下發現文章很少,於是寫篇文章記錄一下。

原來代碼:

let mongoose = require('./mongodb');
let Schema = mongoose.Schema;
var ArticleSchema = new Schema({
    author: { type: String, default: 'admin' }, //作者
    time: { type: Date, default: Date.now }, //時間 
    content: { type: String, required: true }, //內容
    img: { type: String, default: 'logo.svg' },
    zan: { type: Number, default: 0 },
    cai: { type: Number, default: 0 },
    read: { type: Number, default: 0 },
    category: [String],
    ///////////////////
    // comment這裏是重點
    ///////////////////
    comment: [{
        name: { type: String, default: '路人' },
        time: { type: Date, default: Date.now },
        content: { type: String, required: true }
    }]
});
module.exports = mongoose.model('Article', ArticleSchema, 'article');

我打算插入一條評論:

router.post('/pushCommentById', async (ctx) => {
    const id = ctx.request.body.id

    // 新建評論
    const comment = {
        name: ctx.request.body.name || '路人',
        time: Date.now
        content: ctx.request.body.content
    }

    // 插入評論
    const data = await Article.findByIdAndUpdate({ '_id': id }, { $push: { comment } }, {                 new: true });
    console.log(data)
    ctx.body = data;
})

然後就報錯:

解決方式

將Date.now去除掉

const comment = {
        name: ctx.request.body.name || '路人',
        // time: Date.now,
        content: ctx.request.body.content
    }

原因分析

我新建的comment的格式與原來Schema裏聲明的不一樣,Scema裏的是Date對象,我傳入的Date.now是一個函數,類型不同。

Scema裏的Date.now是在沒有值的情況下執行該函數,並非值是函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章