简体   繁体   中英

User specific calculated attibute in MEAN.js MongoDB query

I'm building an Restful API using Mean.js.

I have an Article Model:

var ArticleSchema = new Schema({
    title: { ... },
    content: {...},
    ...
}

And an User Model, which has an array of the Articles the user bookmarked.

var UserSchema = new Schema({
    name: { ... },
    ...
    bookmarks: [{ type: Schema.ObjectId, ref: 'Article' }]
}

I want to attach to the Articles objects retrieved from the DB a calculated boolean attibute 'Bookmarked', indicating if the logged user has bookmarked the article.

I'll also have to repeat the logic to show which articles the user has already read, and which ones are new to him, and maybe an attribute to rate or like/dislike the article. All of them involving the same problem.

How can I do this? How the best way?

I can do this on the DB level or Express level. I'm trying to send to the user the field already calculated in the JSON he'll receive.

I'm open to any solutions, and willing to change the model, relationships or the logic if necessary.

I will suggest something like this;

var ArticleSchema = new Schema({
    title: { ... },
    content: {...},
    ...
    bookmarkedBy : [{ type: Schema.ObjectId, ref: 'User' }]
    readBy : [{ type: Schema.ObjectId, ref: 'User' }]
    likedBy : [{ type: Schema.ObjectId, ref: 'User' }]
    dislikedBy : [{ type: Schema.ObjectId, ref: 'User' }]
}

var UserSchema = new Schema({
    name: { ... },
    ...
    bookmarks: [{ type: Schema.ObjectId, ref: 'Article' }]
    likes: [{ type: Schema.ObjectId, ref: 'Article' }]
    dilikes: [{ type: Schema.ObjectId, ref: 'Article' }]
    bookmarks: [{ type: Schema.ObjectId, ref: 'Article' }]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM