2017-12-09 14 views
0

블로그 서버의 코멘트 배열에 코멘트를 저장하는 Mongoose와 Mongo를 사용하여 노드 서버에서 경로를 만들고 있습니다 (모델 코드 게시 예정). 나는 그것이 나에게 다음과 같은 오류를 제공 쿼리를 실행하려고 할 때 : Postman error
이 내 모델과 경로입니다Mongoose의 배열에서 객체를 푸시하는 방법 (오류)

블로그 게시물 모델

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

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, 
    title: String, 
    user: { type: Schema.Types.ObjectId, ref: 'user' }, 
    board: {type: Schema.Types.ObjectId, ref: 'board'}, 
    comments: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'comment' 
    }] 
}); 

const BlogPost = mongoose.model('blogPost', BlogPostSchema); 

module.exports = BlogPost; 

코멘트 모델

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

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 
}); 

// UserSchema.virtual('postCount').get(function(){ 
// return this.posts.length; 
// }); 

const Comment = mongoose.model('comment', CommentSchema); 

module.exports = Comment; 

Route

routes.put('/blogPosts/:id/comment', function(req, res) { 
    const blogPostId = req.param('id'); 
    const commentProps = req.body; 

    BlogPost.findById(req.params.id) 
     .then((blogPost) => { 
      blogPost.comments.push(commentProps); 
      blogPost.save(); 
     }) 
    .catch((error) => res.status(400).json(error)) 
}); 

모든 도움을 주시면 감사하겠습니다.

+0

https://docs.mongodb.com/ecosystem/use-cases/storing-comments/ 그것의 파이썬하지만 당신은 $ push를 사용하여 아이디어를 얻을 – Gntem

답변

1

문제는 당신 만하며 Object를하기로했다 배열로 전체 주석 개체를 추진한다는 것이다.

dnickless answer은 참조가있는 솔루션을 사용합니다. 즉, 블로그 게시물 모음 및 의견 모음이 있다는 의미입니다. blogpost 문서는 objectids로 주석을 참조합니다.

블로그 참조 모델을 참조하는 대신 포함을 사용하도록 변경할 수도 있습니다. 즉, 주석은 blogpost 문서의 일부로 하위 문서로 사용됩니다. herehere에 대한 좋은 토론이 몇 가지 있습니다. 간단히 대답하면 유스 케이스에 달려있다. 자신이 사용하고자하는 것을 선택할 수 있습니다.

여기에 삽입이 이루어집니다 방법은 다음과 같습니다

블로그 게시물 모델 : 코멘트 배열이 객체 식별자의 배열되는 것이 아니라 주석 스키마를 사용하는 방법

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 
const commentSchema = require('./comment.model'); 

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, 
    title: String, 
    user: { type: Schema.Types.ObjectId, ref: 'user' }, 
    board: {type: Schema.Types.ObjectId, ref: 'board'}, 
    comments: [commentSchema] 
}); 

const BlogPost = mongoose.model('blogPost', BlogPostSchema); 

module.exports = BlogPost; 

알 수 있습니다. 주석 모델은 약간 변경 될 수 있습니다

코멘트 모델 :

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

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 
}); 

// UserSchema.virtual('postCount').get(function(){ 
// return this.posts.length; 
// }); 

module.exports = CommentSchema; 

const Comment = mongoose.model('comment', CommentSchema);이 제거되었다. 스키마는 더 이상 등록되지 않아야하며 주석에는 자체 컬렉션이 없습니다. 이제 등록 된 모델이 아닌 스키마가 내보내집니다.

주석을 추가하는 원래 코드는 그 후에 작동합니다. 댓글은 블로그 게시물의 일부가되며 자신의 컬렉션에 포함되지 않습니다.

+0

내가 하위 방법을 통해 그것을 할 경우, 나는 여전히 얻을 수 사용자의 의견 목록?아니면 blogPost는 댓글에 대한 액세스 권한 만 갖고 있습니까? – Mike

+0

@Mike 여전히 사용자의 댓글 목록을 얻을 수 있지만 별도의 컬렉션에 댓글이있을 때보 다 조금 어렵습니다. 정규화 된 모델 (참조)은 사용하기가 더 쉽고 비정규 화 된 모델 (포함)은 다른 수집을 참조 할 필요가 없으므로 올바르게 수행하면 읽기 성능이 향상 될 수 있습니다. 여기 [https://www.mongodb.com/blog/post/thinking-documents-part-1?jmp=docs&_ga=2.97543773.31888329.1512825673-1213879524.1495890610]에 대한 자세한 정보가 있습니다. – MikaS

0

전체 commentcomments 배열로 밀어 넣지 않고 단지 _id으로 푸시하고 싶지는 않습니다. 이 (안된) 같은 일이 :

// first save the comment 
Comment.create(commentProps, function(err, comment) { 
    if(err) 
    { 
     // save the world 
    } 
    else 
    { 
     BlogPost.update({ _id: req.param('id') }, { $push: { comments: comment._id } }, function(err, numberAffected, raw) { /*...*/ }); 
    });