如何使用正确嵌套的mongoose模型和模式

时间:2017-07-21 08:11:10

标签: node.js mongodb mongoose

这是我的架构。我是mongoose的新手但是尝试了政策为什么在不需要时发送额外信息。我曾尝试过一个subDocument来评论和喜欢。

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并正确地获取数据,我会很高兴并且可以完成剩下的工作。

1 个答案:

答案 0 :(得分:0)

您只能在likescount: {type: Number}字段中添加comments,并在.push新对象转到likes字段时将此字段增加。