2017-07-21 109 views
0

這是我的模式。我對貓鼬是新手,但嘗試政策爲什麼不需要時發送額外的信息。我曾嘗試爲評論和喜歡做一個子文檔。如何正確使用嵌套貓鼬模型和模式

var post = new Schema({ 
    postid: {type: Number, required: true, unique: true}, 
    title: {type: String, required: [true, 'Title cannot be blank']}, 
    startdate: {type: Date, required: true, default: Date.now}, 
    enddate: {type: Date, required: true, default: new Date(+new Date() + 15 * 24 * 60 * 60 * 1000)}, 
    comments: [ 
     { 
      id: {type: Number, required: true}, 
      message: {type: String, required: true}, 
      userid: {type: String, required: true, unique: true}, 
      updated_at: {type: Date, required: true, default: Date.now, select: false}, 
      likes: [ 
       { 
        userid: {type: String, required: true, unique: true}, 
        updated_at: {type: Date, required: true, default: Date.now}, 
       } 
      ], 
     } 
    ], 
}, { 
    timestamps: { 
     createdAt: 'created_at', 
     updatedAt: 'updated_at' 
    } 
}); 

post.index({postid: 1}); 

我做一些骯髒的詭計利用lean()以獲得REST API的數據。

// post [GET] 
[ 
    { postid: 1, title: "dfdsfadsf", startdate: "dafdsfadsf", enddate: "dsafdsfads", commentscount: 6}, 
    { postid: 2, title: "ffdsfadsf", startdate: "dafdsfadsf", enddate: "dsafdsfads", commentscount: 5}, 
] 
// post/:id [GET] 
{ 
    postid: 1, 
    title: "dfdsfadsf", 
    startdate: "dafdsfadsf", 
    enddate: "dsafdsfads", 
    comments: [{ 
     {id: 1, message: "ddsfsfadsfa", likescount: 6}, 
     {id: 2, message: "dsfafdrsdsfa", likescount: 3}, 
     {id: 3, message: "dsfaefdsdsfa", likescount: 4}, 
     {id: 4, message: "dfsfdsfadsfa", likescount: 5}, 
     {id: 5, message: "fdsfdsfadsfa", likescount: 7}, 
     {id: 6, message: "dsfadwsfadsf", likescount: 0} 
    }] 
} 
// post/:id/comments/:commentid/likes [GET] 
{ 
    id: "1", 
    message: "fadsfads", 
    likes: [ 
     { userid: 1, updated_at: "some date" }, 
     { userid: 2, updated_at: "some date" }, 
     { userid: 3, updated_at: "some date" }, 
     { userid: 4, updated_at: "some date" }, 
     { userid: 5, updated_at: "some date" }, 
     { userid: 6, updated_at: "some date" } 
    ] 
} 

下使用mysql這是很容易使用ORM,做這一切與一個單一的查詢。現在,貓鼬,我在一個糟糕的方式這樣做,就像

第一路由,我做的我做了其他兩條航線

Posts.find({}).select({ 
    postid: true, 
    title: true, 
    startdate: true, 
    enddate: true, 
    comments: true 
}).lean().exec(function(err, doc){ 
    if (doc) { 
     if(doc.comments.length > 0) { 
      doc.commentcount = doc.comments.length; 
      delete doc.comments; 
     } 
    } 
}); 

同樣的方式。我覺得可能有一種使用貓鼬模型來完成所有這些工作的正確方法。我曾嘗試使用aggregate & populate。但不是我的小菜一碟。

如果任何人都可以指導如何使用ORM並正確獲取數據,我會很高興,並可以完成剩下的工作。

回答

0

您只能在comments字段中添加likescount: {type: Number}字段,並在.push新對象字段爲likes時遞增此字段。

+0

對於維持那個部分就像新創造增量一樣,在刪除遞減方面不會是額外的負擔。 – Priya