I would like to setup a "like" system in my app. User should be able to like either Posts or Comments (Comments of a Post of course). How should I design this?
Users
const userSchema = new Schema({
id: { type: String, required: true },
username: { type: String, required: true },
password: { type: String, required: true },
});
Posts
const postSchema = new Schema({
content: { type: String, required: true },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }
});
Comments
const commentSchema = new Schema({
content: { type: String, required: true },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: true },
});
Likes
const likeSchema = new Schema({
content: { type: String, required: false },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: function() { return this.commentId? false : true } },
commentId: { type: mongoose.Schema.Types.ObjectId, ref: "Comment", required: function() { return this.postId? false : true } }
});
I'm coming from relational databases, and maybe my design is completely wrong for nosql. My main interrogation is about Likes, I have no idea how to accept likes on Posts OR Comments.
I would prefer a separate collection:
User:
id:
...
Post:
id:
userId:
...
Comment:
id:
userId:
postId:
Like:
id:
userId:
postId:
commentId:
The second one storing an array will lead you cyclic dependencies in the backend. Especially, when you use NodeJS and strict to flow.
MongoDB is powerful at storing documents. Documents hold the relations.
I would model it in the way your data is being accessed. I do recommend playing around with the powerful aggregation framework and array operators to experience the possibilities. What I would explore is the following
User:
id:
name:
picture:
...
Posts:
id:
authorid:
content:
total_views:
tags: array of String
likes: array of Likes {[
liked_by: user_id
],...}
comments: array of Comments {[
author_id: ...
comment: ...
reactions: array of Comments {[],...}
likes: array of Likes {[
liked_by: user_id
],...}
],...}
Will this model scale? Documents can hold 16MB of data. 16MB in textual format is HUGE.
PS please think again on storing username/password in the database. This is a whole other discussion. Look into the topics of authentication, authorisation, OAuth, hashing/salting etc.
post={
...keys,
likes:[likeSchema],
comments:[CommentSchema]
}
this is i prefer, even if you want to store recursive comments just use
commentschema={
id:unique commet id
text:...
user_id:who wrote this comment
parent_id: to which this comment belongs to!
depth: comment depth as your wish (mostly 2)
}
parent id will be null for a comment posted directly on post
parent id will be comment_id of the comment to which this comment posted for. if its a recursive comment.
hope you get it.
Since, the question is about schema for like a comment or post. I'll focus on likes.
Build a schema like this. Here targetId will be postId or commentId.
const likeSchema = new Schema({
content: { type: String, required: false },
authorId: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
targetId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: function() { return this.commentId? false : true } }
});
Some points you need to consider:
Store likes of posts in post collection
Store likes of comments in comments collection
You need to build a mechanism to calculate likes and store in that collection
Related
My service uses MongoDB and Mongoose. I have two DBs: Users and Posts. In Posts schema I have parameters:
"author", that contains userId from Users DB
"anonymous", a boolean-parameter that shows if the post is anonymous or not.
I can't solve the problem: when I request data from Posts DB I want to populate author in the "author" parameter only for non-anonymous posts, for anonymous ones I'd like to return null or not to return this parameter at all.
I've tried to use "match", but it doesn't work.
How can I solve this problem?
Thank you.
Code example:
const postSchema = mongoose.Schema(
{
author: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
anonymous: {
type: Boolean,
required: true,
default: false,
},
content: {
type: String,
required: true,
},
date: {
type: Date,
required: true,
default: Date.now,
},
},
{
timestamps: true,
}
);
For population I use pre:
postSchema.pre(/^find/, function (next) {
this.populate({
path: 'author',
select: '_id login',
});
next();
});
What I want is that a user can like a post only once, hence I uniquely indexed the user in the likes array to ensure the same, but it isn't working and I can't find out what is wrong here .
The schema looks like this :
const mongoose = require('mongoose')
const postSchema = new mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User' // User model
},
text: {
type: String,
required: [true, 'Post must have some text']
},
likes: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}
],
comments: [
{
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
text: {
type: String,
required: [true, 'Comment must have some text']
},
addedAt: {
type: Date,
default: Date.now
}
}
],
createdAt: {
type: Date,
default: Date.now
}
})
postSchema.pre(/^find/, function(next) {
this.populate({
path: 'author',
select: 'name avatar'
}).populate({
path: 'comments.author',
select: 'name avatar'
})
next()
})
// Ensure a user can like a post only once
postSchema.index({ 'likes.user': 1 }, { unique: true })
const Post = mongoose.model('Post', postSchema)
module.exports = Post
However when I send a post request to like a post twice via the same user it
shows no error.
Here is the postman output
I have tried both the ways listed in this, but none of them worked in this case.
Mongoose Index on a field in nested document
How do I ensure a user can like a post only once from the schema itself ?
Try saving likes in this format in the database
likes:[{type:mongoose.Schema.Types.ObjectId,ref: 'User'}]
making it
likes:[ObjectId("5af03111967c60501d97781f")]
and when the post like API is hit do
{$addToSet: {likedBy: userId}}
in update query,addToSet ensures no duplicate ids are maintained in the array.
**I have answered below. In short you need to require the Model in the module in which you wish to populate, even though you do not refer to it directly.
I am hitting a strange problem with mongoose when populating just one particular array of IDs.
I have three models, User, Company and Widgets.
When I return the company populated with the users all is fine using:
Company.findOne({ name: 'xyz' })
.populate('users')
.exec(function(err, company) {
if (err) return res.send(err)
res.send(company)
})
However when I try to replace populate 'users' with 'widgets' I get the following error:
{
"message": "Schema hasn't been registered for model \"widget\".\nUse mongoose.model(name, schema)",
"name": "MissingSchemaError"
}
Here are the models:
USER:
const UserSchema = new Schema({
name: String,
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
company: {
type: Schema.Types.ObjectId,
ref: 'company'
}
});
const User = mongoose.model("user", UserSchema);
COMPANY:
const CompanySchema = new Schema({
name: String,
URL: {
type: String,
unique: true
},
users: [{
type: Schema.Types.ObjectId,
ref: 'user'
}],
widgets: [{
type: Schema.Types.ObjectId,
ref: 'widget'
}]
});
const Company = mongoose.model('company', CompanySchema);
WIDGET:
const WidgetSchema = new Schema({
title: {
type: String,
required: true
},
maker: String
});
const Widget = mongoose.model('widget', WidgetSchema);
I have manually inspected the _ids in the widget array of the company model and they are all correct.
OK, so this was a lack of understanding on my behalf.
In the module where I was using:
Company.findOne({ name: 'xyz' })
.populate('users')
.exec(function(err, company) {
if (err) return res.send(err)
res.send(company)
})
I had imported the User model for other uses in the module. However, as I was not directly referring to Widget I had not imported it. Having done some more research I found that you need to import a model when populating even though not referring to it directly.
Let me know if best to delete whole thread or leave for reference.
I have this schema:
var PostSchema = new Schema({
by: { type: mongoose.Schema.Types.ObjectId, ref:'user' },
body: String,
likes: [{ by: { type: mongoose.Schema.Types.ObjectId, ref:'user' }, isAnonymous: { type: Boolean, default: false}}],
});
This schema supports anonymous likes.
my question: is there a way to populate only the items in the 'likes' array where isAnonymous is equals to false?
Yes, There is
opts={
path: 'likes',
match: {
isAnonymous:false
},
select: '<fields to be fetched>'
};
Post
.find({})
.populate(opts)
docs
help
I have a project am working on. I have a comment schema, a likes schema and a blog schema. All three are declared as separate schemas but the likes and comments schema are then nested into the blogs schema as children i.e comments: [CommentSchema]. Now i have a page where when someone clicks on a blog it displays all the comments together with the blog. This the code that gets the blog Blog.findById(id).populate('user', 'username').exec(function(err, blog). Now in the comments array there is a key called commOwner that refers to the objectid from another schema called user just like the blog schema has a reference key too as u can see from the code. I am trying to display the gravatar and username of each person that made a comment based on the reference key commOwner that's in the comments schema but i don't know how to go about it. I want to also be able to populate the usernames and gravatar of those who commented on the blog in that same code where i did it for the blog. Please can someone help me with this. below is the code for all my schemas
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/*Comment schema*/
var CommentSchema = new Schema({
commOwner: {
type: Schema.ObjectId,
ref: 'User'
},
commbody: {
type: String,
default: '',
trim: true,
//required: 'Comment cannot be blank'
},
updated: {
type: Date,
default: Date.now
}
});
/**
* Likes Schema
*/
var LikeSchema = new Schema({
score : {
type: Number,
default: 0
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
/**
* Blog Schema
*/
var BlogSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
//required: 'Content cannot be blank'
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
comments: [CommentSchema],
likes: [LikeSchema]
});
mongoose.model('Blog', BlogSchema);
Blog.findById(id).
populate(
[{path:'user', select:'username'},
{path:'comments.commOwner',select:'username profilepic ...'}])
.exec(function(err, blog){...})
In the select field specify other fields( separated by spaces ) to be populated in commOwner.
Have a look at the docs