How to fetch posts by user and all his followings posts (Mongodb, Mongoose, Nodejs)
User Schema
const userSchema = new mongoose.Schema({
firstName: { type: String, required: true, trim: true },
lastName: { type: String, required: true, trim: true },
});
userSchema.set('timestamps', true);
export default mongoose.model('user', userSchema);
Followers Schema
const followSchema = new mongoose.Schema({
follower: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
following: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
status: { type: Boolean, default: true }
});
followSchema.set('timestamps', true);
export default mongoose.model('follow', followSchema);
Posts Schema
const postSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
contents: { type: String, trim: true },
photo: { type: String }
});
postSchema.set('timestamps', true);
export default mongoose.model('post', postSchema);
Thank you in advance! :)
Hy Alamghir its happy to see you here and sorry that you still did not get the answer what i can suggest you after seeing your schema that i think there is no need to create three collections you only need 2 schema first one
const userSchema = new mongoose.Schema({
firstName: { type: String, required: true, trim: true },
lastName: { type: String, required: true, trim: true },
followers:[]
});
userSchema.set('timestamps', true);
export default mongoose.model('user', userSchema);
Now in followers array just push the ids of users who followed this user Now it would be very easy for you to get posts done by these people like this let suppose you have user data in userData variable now you can do this
db.postSchema.find($or:[{userId:userData._id},{userId:$in:userData.followers}])
Sorry, got your question wrong.
There might be a better solution but what you should be able to do is this:
(this gets the posts of the people that are following your original user. If you did mean it the other way around, just switch :) )
// get the user's posts:
var theUserPosts = await postSchema.find({userId: userData._id}).exec();
// get the follower-IDs:
var theFollowersIDs = await followSchema.find({follower: userData._id, status: true}, 'following').exec();
// get the posts of those followers:
var followerPosts = await postSchema.find({userId: {$in: theFollowersIDs}}).exec();
Can you try this and tell us if this works for you?
Related
I am creating an application with some functionality similar to twitter where the user posts text and images.
I want to give the user a default profile picture in case he doesn't have one, but I'm not sure how to do it.
I created a schema image where I wrote the following code but I don't know how to continue to make what I want to implement work:
'use strict';
const mongoose = require('mongoose');
const imageSchema = mongoose.Schema({
photo: { type: Array, default: ['https://wallpapers-clan.com/wp-content/uploads/2022/06/cute-pusheen-pfp-1.jpg'] }
});
This is the user schema I created:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const {Schema} = mongoose;
const saltRounds = 10;
const userSchema = new mongoose.Schema({
name: { type: String, require: true },
username: { type: String, unique: true },
email: { type: String, unique: true },
password: { type: String, require: true },
salt: { type: String, require: true },
followers: [{
type: 'ObjectId',
ref: 'User'
}],
following: [{
type: 'ObjectId',
ref: 'User'
}],
posts: [
{
type: 'ObjectId',
ref: 'Post'
}
]
}, { timestamps: true });
I created a schema image but I'm not sure if I'm on the right track
If your users can only have one profile picture it's not necessary to create a new schema just for the profile picture. You could store the image as an URL in the user schema, that way when you load the user's document you also get their profile picture.
You could add the following field to your existing user schema:
profilePicture: {
type: String,
default: 'https://example.com/cute-pusheen.jpg' // Add a default value
},
In this case if you don't specify an image when creating the user the defualt value will be used.
I have followed the mongoose docs for populating related objects, everytime authSessions is empty. I can see in mongo sessions are being populated along with the related userId field. I have tried specifying ”path” and “model” options in the populate function as well but that didn’t work either. Anyone have any ideas?
//Session.js
const SessionSchema = new mongoose.Schema({
_id: Schema.Types.ObjectId,
sessionId: { type: String, index: true },
createdDate: { type: Date, default: Date.now },
revoked: Boolean,
revokedAt: Date,
userId: {type: Schema.Types.ObjectId, ref: 'User', index: true}
})
module.exports = mongoose.models.Session || mongoose.model('Session', SessionSchema);
//User.js
const UserSchema = new mongoose.Schema({
_id: Schema.Types.ObjectId,
username: { type: String, index: true },
email: { type: String, index: true },
password: String,
registrationDate: { type: Date, default: Date.now },
authSessions: [{type: Schema.Types.ObjectId, ref: 'Session'}]
})
module.exports = mongoose.models.User || mongoose.model('User', UserSchema);
const user = await User.findById(session.userId).populate('authSessions').exec();
console.log(user) //authSessions is empty
{
_id: new ObjectId("62b6ea393e042868caa68c7d"),
username: 'asdfasdfasdf',
email: 'testaskldjflk#djlkajdf.com',
password: 'testaskldjflk#djlkajdf.com',
authSessions: [], //empty here always
registrationDate: 2022-06-25T10:58:01.709Z,
__v: 0
} ```
MongoDB, and by extension mongoose, doesn't automatically create relations for you.
If you create a Session document, you need to explicitly add it to a User document if you want populate to work:
// create a new session document and save it
const userSession = new Session(…);
await userSession.save();
// !! update the user document and save it
user.authSessions.push(userSession);
await user.save();
I have two tables: Post and User and I want to reference the User name in the Post table.
I can reference the ID but I also need the name.
User model:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
})
module.exports = mongoose.model("User", userSchema)
Post model:
const { ObjectId } = mongoose.Schema.Types
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
author: {
type: ObjectId,
ref: "User",
},
})
module.exports = mongoose.model("Post", postSchema)
In the doc they said:
Note: ObjectId, Number, String, and Buffer are valid for use as refs.
However, you should use ObjectId unless you are an advanced user and
have a good reason for doing so.
However I couldn't find an example on how I can do this.
I'm trying to embed a model in a mongoose schema. Here's what I have:
const People = {
userId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'User'
},
locationId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'Location'
},
};
const Person = mongoose.model(
'Person',
new mongoose.Schema({
...People,
gender: {
type: String
}
})
);
const shmanian = await new Person({gender: 'other', userId:'someUserId', locationId: 'someLocationId'}).save();
The response I get is {gender: 'other'}
The problem is that people doesn't get populated when I create Person.
You should embed an array of "Person" inside a model "People". For example,
const Schema = require("mongoose").Schema;
const model = require("mongoose").model;
const Person = new Schema({
userId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'User'
},
locationId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'Location'
},
});
const People = new Schema({
person: [Person]
});
module.exports = model("People", People);
Here, everytime you create a new Person, you can add it to the People model which contains an array of Person objects.
Not a mongoose Problem.
People is undefined when you create the Object Person.
Thus it doesn't get populated.
Try switching both assignments.
I had created one index on the collection and it was created. But after the drop that collection and when I restarted node server then collection are created again but the index isn't can anybody suggest what is the cause?
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const validator = require('validator')
const FeatureSchema = new Schema({
name:{
type: String,
trim: true,
required: "Please enter a feature name!"
},
slug: String,
description: {
type: String,
trim: true
},
author: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'You must supply an author'
},
productID: {
type: mongoose.Schema.ObjectId,
ref: 'Product',
required: 'You must supply an product'
}
},{
timestamps: {
createdAt: 'createdDate',
updatedAt: 'updatedDate'
}
});
// Define our indexes
FeatureSchema.index({
name: 'text'
});
module.exports = mongoose.model('Feature', FeatureSchema);
try to stop mongodb service and restart it again.