2017-12-06 18 views
1

私はmongoDBを持っており、データベース内のデータを操作するNodejsサーバーを作ろうとしています。 BlogPostオブジェクトのComments配列にコメントをプッシュしようとすると、私はcastErrorを取得します。MongoDBとNodejsの配列にオブジェクトをプッシュしようとすると、なぜcastErrorが返されますか?

以下のソースコードは、重要な情報が不足している場合は教えてください。 ありがとうございます!

経路:

routes.post('/comments/push/:id', function(req, res) { 
const blogPostId = req.param('id'); 
const commentProps = req.body; 

BlogPost.findById(blogPostId) 
    .then((blogPost) => { 
    blogPost.comments.push(commentProps); 
    return blogPost.save(); 
    }) 
    .then((blogPost) => res.status(200).json({ 
    'status': 'Comment is deleted.', 
    'comment': blogPost 
})) 
.catch((error) => res.status(400).json(error)) }); 

ブログ投稿スキーマ:

const BlogPostSchema = new Schema({ 
content: { 
type: String, 
validate: { 
    validator: (content) => content.length > 5, 
    message: 'Content must contain at least 6 characters.' 
}, 
required: [true, 'Content must be filled in.'] 
}, 
rating: Number, 
user: { type: Schema.Types.ObjectId, ref: 'user' }, 
board: {type: Schema.Types.ObjectId, ref: 'board'}, 
comments: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'comment' 
    }] 
}); 

コメントスキーマ:

const CommentSchema = new Schema({ 
content: { 
type: String, 
validate: { 
    validator: (content) => content.length > 5, 
    message: 'Content must contain at least 6 characters.' 
}, 
required: [true, 'Content must be filled in.'] 
}, 
user: { type: Schema.Types.ObjectId, ref: 'user' }, 
rating: Number 

// board: Board 
}); 

ここでは、郵便配達の誤差である: postman screen

大歓迎です!

答えて

0
  1. 最初にreq.bodyで何が受信されているかを確認してください.req.bodyから直接保存するには、 が不十分です。
  2. 第2 ref。コメントスキーマaspect a objectId req.bodyが オブジェクトそのものです。私はあなたが何をしようとしているのかはわかりませんが、 blogPost.comments.push(req.body.someValidId)のようなものです。

3番目なぜ簡単な更新のための2つのクエリ。 $ push、$ addToSetを使って直接コメントにプッシュしたり、$ pullを使ってコメントから削除することができます。

BlogPost.findOneAndUpdate({ 
    _id:blogPostId 
}, { 
    $addToSet:{ 
     comments : someValidId 
    } 
}, { 
    new :true, 
    upsert:false 
}) 
.then((blogPost) => { 
    res.status(200).json({ 
     'status': 'Comment is deleted.', 
     'comment': blogPost 
    }) 
}) 
.catch((error) => 
    res.status(400).json(error)) 
}); 
関連する問題