2017-12-06 1 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' 
    }] 
}); 

주석 스키마 : postman screen

,369 : 여기
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 
}); 

은 우체부에 오류가

도움을 주시면 대단히 감사하겠습니다!

답변

0
  1. 먼저 req.body에서받는 것을 확신, 그것은 req.body에서 직접 저장 좋지 않아 확인하십시오.
  2. 두 번째 참조 주석 req.body가 객체 자체 인 동안 스키마 aspect는 objectId입니다. 나는 당신이 무엇을 하려는지 확실하지 않지만 blogPost.comments.push (req.body.someValidId)와 같은 것을;

세 번째 이유 간단한 업데이트 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)) 
}); 
관련 문제