I have created two models in nodejs, which are: User and Auth.
In the User model will be stored the user name and an array of authentication objects that is reference of the Auth model.
In the Auth model will be stored the token generated by JWT and the creation date of the token ...
Rules:
Each user can have multiple authentication token, but each token will be unique as soon as the token expires, it will be aborted in the database, but the creation date should remain.
What's my problem?
1) I'm having cast problem in Array.
2) I do not know how to go through this Array of Objects, starting with the auth token and the specific username.
const mongoose = require('mongoose');
class AuthModel {
createSchema(){
const authSchema = new mongoose.Schema({
token: {
type: String,
unique: true,
required: true
},
createAt: {
type: Date,
default: Date.now
}
});
return authSchema;
}
}
module.exports = mongoose.model('AuthModel', new AuthModel().createSchema());
const mongoose = require('mongoose');
class UserModel {
createSchema(){
const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
auth: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'AuthModel',
required: true,
}]
});
return userSchema;
}
}
module.exports = mongoose.model('UserModel', new UserModel().createSchema());
1: //define embedded schema
const authSchema = new mongoose.Schema({
type: mongoose.Schema.Types.ObjectId,
ref: 'AuthModel',
required: true,
});
const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
auth: [authSchema] // add embedded schema here
});
2 . When you fetch userModel, you will be required to populate( mongoose function) auth model
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 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;
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 created two models where I am trying to ref one model to another but it's not working and I don't have any idea about it I used it exactly the same way as in the mongoose example but it is not helping, the only difference between my working and their example is I have two different files for both models and I am exporting them to use in another file
The example I took reference from Mongoose
First Model
const userModel = require('./userModel')
const {Schema} = mongoose
const tweet = new Schema({
date: {
type: Date,
required: true,
},
msg:{
type: String,
maxlength:140,
required:true
},
tweetid:{
type: mongoose.Types.ObjectId
}
})
const tweetSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'userModel'
},
tweets: {
type: [{tweet}],
default: []
}
})
const tweetModel = mongoose.model('tweet',tweetSchema)
module.exports = tweetModel
Second Model
const {Schema} = mongoose
const userSchema = new Schema({
email: {
type:String,
required: true,
unique: true,
trim:true
},
password: {
type:String,
required: true,
trim:true
},
follows: {
type: [String],
default: []
}
})
const userModel = mongoose.model("User",userSchema)
module.exports = userModel
Your reference string should be equal to the model name that you have passed to mongoose.model:
const tweetSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
tweets: {
type: [{tweet}],
default: []
}
})
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.