How do I fetch User post on user timeline? - node.js

I have a database containing 3 collections [Users (contains registered users), Userpost (contains the post of the registered users) while Profile (contains their individual profile)].
I was able to link the Profile and Users Schemas to the Userpost Schema with their ObjectId.
What I know at present is how to fetch the Userpost and populate the User and Profile.
What I want to do is to fetch all the post of a single registered user his/her timeline.
What I have tried to the add the Userpost and Profile Schemas to the UserSchema by the ObjectId but each time I make a post, the Userpost on the User collection is always an empty array.
Below are my Schemas please
User Schema
const userSchema = new Schema({
username: {
type: String,
required: true
},
roles: {
User: {
type: Number,
default: 2001
},
Mentor: Number,
Admin: Number
},
password: {
type: String,
required: true
},
userID: {
type: String,
required: true
},
refreshToken: String
});
const User = mongoose.model('user', userSchema);
module.exports = User;
Profile Schema
const ProfileSchema = new Schema({
lastname: {
type: String,
required: true,
},
firstname: {
type: String,
required: true,
},
othernames: {
type: String,
required: true,
},
countries: {
type: String,
required: true,
},
phones: {
type: String,
required: true,
},
User: [{
type: Schema.Types.ObjectId,
ref: 'user',
required: true,
}],
});
const Profile = mongoose.model('profile', ProfileSchema);
module.exports = Profile;
UserPost Schema
const UserpostSchema = new Schema({
post: {
type: String,
required: true
},
Profile: [{
type: Schema.Types.ObjectId,
ref: 'profile',
required: true,
}],
User: [{
type: Schema.Types.ObjectId,
ref: 'user',
required: true,
}]
});
const Userpost = mongoose.model('userpost', UserpostSchema);
module.exports = Userpost;
How I populate User and Profile to the UserPost on API
router.get('/getpost/:id', (req, res) => {
const id = req.params.id;
Userpost.find({_id:id}).populate('User').populate('Profile').exec((err,docs) => {
if(err) throw(err);
res.json(docs);
})
});
How do I fetch the entire post of a user to his timeline?
Kindly help please.
Thanks and regards

This should work for u, In UserPost Schema you have taken array for Profile and User which isn't required, and also instead of Schema use mongoose.Schema every where in model.
User Schema
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
roles: {
User: {
type: Number,
default: 2001
},
Mentor: Number,
Admin: Number
},
password: {
type: String,
required: true
},
userID: {
type: String,
required: true
},
refreshToken: String
});
const User = mongoose.model('user', userSchema);
module.exports = User;
Profile Schema
const mongoose = require("mongoose");
const ProfileSchema = new mongoose.Schema({
lastname: {
type: String,
required: true,
},
firstname: {
type: String,
required: true,
},
othernames: {
type: String,
required: true,
},
countries: {
type: String,
required: true,
},
phones: {
type: String,
required: true,
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
required: true,
},
});
const Profile = mongoose.model('profile', ProfileSchema);
module.exports = Profile;
UserPost Schema
const mongoose = require("mongoose");
const UserpostSchema = new mongoose.Schema({
post: {
type: String,
required: true,
},
Profile: {
type: mongoose.Schema.Types.ObjectId,
ref: "profile",
required: true,
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
required: true,
},
});
const Userpost = mongoose.model("userpost", UserpostSchema);
module.exports = Userpost;

Related

populate() doesn't fetch referenced profile instead it fetches the first profile in my collection

I have three collections which are User, Profile and Userpost and all referenced accordingly. The challenge I am facing is that when I use the .populate(), instead of fetching the Profile information of the logged in user, it fetches the data of the first profile on the profile collections and it does so for any user that is logged in. Kindly help me resolve. Thanks
How I populate
router.get('/getpost/:id', (req, res) => {
const id = req.params.id;
Userpost.find({User:id}).populate('Profile').populate('User', {password: 0}).exec((err,docs) => {
if(err) throw(err);
res.json(docs);
})
});
UserpostSchema
const UserpostSchema = new Schema({
post: {
type: String,
required: true
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
required: true,
},
Profile: {
type: mongoose.Schema.Types.ObjectId,
ref: 'profile',
required: true,
}
});
const Userpost = mongoose.model('userpost', UserpostSchema);
module.exports = Userpost;
Profile
const ProfileSchema = new Schema({
lastname: {
type: String,
required: true,
},
firstname: {
type: String,
required: true,
},
othernames: {
type: String,
required: true,
},
countries: {
type: String,
required: true,
},
phones: {
type: String,
required: true,
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
required: true,
},
});
const Profile = mongoose.model('profile', ProfileSchema);
module.exports = Profile;
and User
const userSchema = new Schema({
username: {
type: String,
required: true
},
roles: {
User: {
type: Number,
default: 2001
},
Mentor: Number,
Admin: Number
},
password: {
type: String,
required: true
},
userID: {
type: String,
required: true
},
refreshToken: String
});
const User = mongoose.model('user', userSchema);
module.exports = User;

post author Id turn into author username in node js for mongodb

i am trying to have my post's author's name in frontend. so i want to find the post according to it's user Id. but in model schema i used obejct Id of user in post Schema.
Here is my userSchema:
const mongoose = require('mongoose');
// user schema
const userSchema = new mongoose.Schema(
{
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
name: {
type: String,
trim: true,
},
password: {
type: String,
required: true
},
salt: String,
bio: {
type: String,
trim: true
},
role: {
type: String,
default: 'subscriber'
},
resetPasswordToken: String,
resetPasswordExpire: Date,
},
{
timestamps: true
}
);
module.exports = mongoose.model('User', userSchema);
here is my postSchema model:
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
comments: [{
text: String,
created: { type: Date, default: Date.now },
postedBy: { type: mongoose.Schema.ObjectId, ref: 'User'}
}],
created: {
type: Date,
default: Date.now
},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
},
{
timestamps: true,
},
);
const Post = mongoose.model("Post", PostSchema);
module.exports = Post;
and here is my router for post lists by a specific user id:
exports.postByUser=async(req,res)=>{
try
{
const userID=async()=>{
await User.findById({ _id:req.params.id})
.then(posts=>{
res.status(200).json(posts.name)
})
}
await Post.find({creator: req.params.id})
.then(posts=>{
res.status(200).json(posts)
})
}catch(error){
res.status(500).send({error: error.message});
};
}
router.route('/post/mypost/:id').get(requireSignin,postByUser);
my target is to get a post list where every post's creator would have the user name. how can i achieve that in nodejs?
i have solved this way:
exports.postByUser=async(req,res)=>{
try
{
await Post.find({creator: req.params.id})
.populate({path:'creator', select:'name -_id'})
.then(post=>{
res.status(200).json(post)
})
}catch(error){
res.status(500).send({error: error.message});
};
}
and it worked

How to update a nested array in mongoose?

I am new to the backend and trying to learn by building some stuff but unfortunately, I got stuck.
I want to know if I can update a nested array of objects in Users Schema using Mongoose in an efficient and elegant way.
Users Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
gender: {
type: String,
required: true
},
password: {
type: String,
required: true
},
friends: [{}],
notifications: []
}, {timestamps: true});
module.exports = User = mongoose.model('user', UserSchema);
In the friends' field, I stored friend request with the status of pending
I want if the user whose the request was sent to, hits an endpoint, to accept the request
by changing the status from pending to success.
This is how a friend request was stored:
friendRequest = {
_id: req.user.id,
status: 'pending',
sentByMe: false,
new: true,
inbox: []
}
Thanks as you help me out!!! 🙏🙏🙏
You should first create an additional friendRequest and inbox schemas like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const InboxSchema = new Schema({
user_id: {
type: String,
required: true
},
from_id: {
type: String,
required: true
},
message: {
type: String,
required: true
},
the_date_time: {
type: Date,
required: true
}
});
mongoose.model('Inbox', InboxSchema);
const FriendRequestSchema = new Schema({
user_id: {
type: String,
required: true
},
status: {
type: String,
required: true
},
sentByMe: {
type: Boolean,
required: true,
unique: true
},
inbox: [InboxSchema]
})
mongoose.model('FriendRequests', FriendRequestSchema);
and update your Users schema:
const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
gender: {
type: String,
required: true
},
password: {
type: String,
required: true
},
friends: [FriendSchema],
notifications: [FriendRequestSchema]
}, {timestamps: true});
And then use the friendRequest object
friendRequest = {
_id: req.user.id,
status: 'pending',
sentByMe: false,
new: true,
inbox: []
}
to update the Users collection
Users.update({ _id: user_id }, { $push: { notifications: friendRequest } });
Whenever you have arrays of objects within collections, its best to define additional schemas. You should also consider adding indexes to your collection schemas.
Update:
A FriendSchema would look like this:
const FriendsSchema = new Schema({
friend_id: {
type: String,
required: true
},
friend_name: {
type: String,
required: true
},
friendship_made: {
type: Date,
required: true
}
// you have to define FriendSchema before you define Users since you
// now reference [FriendSchema] in UserSchema
mongoose.model('Friends', FriendSchema);
And so is personA friends with personB?
Users.findOne({ "_id": personA.id, "friends.friend_id": personB.id});

mongoose schema , Invalid schema configuration

i have a schema of user that contain an array of movie
i create a new schema of Movie
but i get error of invalid schema configuration.
what i'm doning worng?
enter code here
const mongoose = require("mongoose");
const Movie = require("./movie-model");
const Schema = mongoose.Schema;
const User = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
movies: { type: Movie },
});
module.exports = mongoose.model("user", User);
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Movie = new Schema(
{
name: { type: String, required: true },
time: { type: String, required: true },
rating: { type: Number, required: false },
priorety: { type: Number, required: true },
},
);
module.exports = mongoose.model("movie", Movie);
in movie-model
module.export = Movie
instead of
module.exports = mongoose.model("movie", Movie);
User has many movies
const mongoose = require("mongoose");
const Movie = require("./movie-model");
const Schema = mongoose.Schema;
const User = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
movies: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "movie",
},
],
});
module.exports = mongoose.model("user", User);
I invite you to read more about One-to-Many Relationships with Embedded Documents
You need to done referencing in User collection
movies: [
type: mongoose.Schema.ObjectId,
ref: 'user'
]
//instead of doing that
movies: { type: Movie },

Populate() specify multiple model

I'm looking to make a populate() on a find() request but specifying multiple models, so if no occurrence is found on the first specified model the population will make on the second.
Here is an example of what I would like to do :
const userSch = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
mail: {
type: String,
required: true,
unique: true,
}
});
const botSch = new Schema({
username: {
type: String,
required: true,
},
token: {
type: String,
required: true,
unique: true,
},
owner: mongoose.Schema.Types.ObjectId
});
const nspSch = new Schema({
name: String,
channels: [channels],
users: [{
id: {
type: mongoose.Schema.Types.ObjectId,
},
bot: {
type: Boolean,
}
}],
});
const channels = new Schema({
name: String,
message: [{
user: {
type: Schema.Types.ObjectId,
},
content: String,
}],
});
const nsp = mongoose.model('namespace', nspSch);
const Auth = mongoose.model('users', userSch);
const BotAuth = mongoose.model('bots', botSch);
function returnMs(nspID, channelID, callback) {
nsp.findOne({'_id': nspID}).populate({
path: 'channels.message.user',
model: 'users' || 'bots',
select: '_id username',
})
.exec(function(err, r) {
...
})
}
If there is ever an npm package, or a solution or even a track to code it, please share it.
Thank you

Resources