これは私のスキーマです。私は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()
を使用して、残りのAPIでデータを取得するために、いくつかの汚い手口をしています。 ORMを使用して1つのクエリでこれらすべてを行うにはかなり簡単だったmysqlの使用
// 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" }
]
}
。今マングースに私は私が他の二つの経路のためにやっている
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の使用方法をガイドし、データを適切にフェッチすることができれば、私は喜んで残りをすることができます。
新規作成増分、削除減分のようにその部分を維持するために余分な負担はかかりません。 – Priya