So I have 2 models, one is users and the other is sessions.
It was initially setup as:
const users = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
username: {type: String, unique: true},
}
);
module.exports = mongoose.model('User', users,);
I then went on and added another model, called sessions,
const sessions = mongoose.Schema({
_id: {type: mongoose.Schema.Types.ObjectId, default: mongoose.Schema.Types.ObjectId, null: false},
user_id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
timestamp: {type: Date},
});
module.exports = mongoose.model('Sessions', sessions);
I then decided, I want to to be able to pull the user's sessions along with the users and added
sessions: [{type: mongoose.Schema.Types.ObjectId, ref: 'SurfSessions', default: null}] to my users model schema.
I quickly learnt that users.findOne(username:admin).populate('sessions') isn't gonna fill up sessions by itself, as sessions returns as an empty array [].
Since I don't have sessions inside users populated with objectid's does that mean I cannot populate sessions or is there another way?
You should be able to do this with virtual populate:
const users = new mongoose.Schema(
{
_id: mongoose.Schema.Types.ObjectId,
username: { type: String, unique: true },
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
module.exports = mongoose.model('User', users);
Then:
userSchema.virtual('sessions', {
ref: 'Session', // model to search in
foreignField: 'user_id',
localField: '_id', // checks where user_id on session === _id on user
});
After this, use .populate('sessions') as normal. For more check this out: https://mongoosejs.com/docs/tutorials/virtuals.html#populate
Related
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();
Making an app with a variety of schemas, many having other objects (Schema.Types.ObjectIds) as their properties.
When doing this, I can access the sub-object's property, as long as that sub-object's property is a string. But I'm having issues with it if that sub-object's property is yet another object (and then I need to query properties from that, string or not). For example, the first works fine:
user schema-> friends property of user (which is a list of user objects) -> username property of friend (which is a string)
But this I'm having issues with, I'm getting a string id and not the actual object**:
user schema-> profilePosts property of user (which is a list of profilePost objects) -> author property of profilePost (which is a user object)** -> author username property of profilePost (which is a string)
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: {type: String, required: true},
password: {type: String, required: true},
friends: [{type: Schema.Types.ObjectId, ref: "User"}],
profilePosts: [{type: Schema.Types.ObjectId, ref: "ProfilePost"}],
friendRequests: [{type: Schema.Types.ObjectId, ref: "User"}],
})
module.exports = mongoose.model('User', UserSchema);
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ProfilePostSchema = new Schema({
date: {type: Date, required: true},
author: {type: Schema.Types.ObjectId, ref: "User"},
content: {type: String, required: true},
comments: [{type: Schema.Types.ObjectId, ref: "ProfilePostComment"}],
likes: [{type: Schema.Types.ObjectId, ref: "User"}],
hostProfile: {type: Schema.Types.ObjectId, required: true,ref: "User"},
})
module.exports = mongoose.model('ProfilePost', ProfilePostSchema);
exports.user_friends_render = async (req,res) => {
try {
const ViewedProfile = await User.find({}, 'username friends profilePosts friendRequests').populate('friends').populate('profilePosts').populate('friendRequests');
res.status(200).json(ViewedProfile);
} catch(error) {
res.status(200).json({message: error.message});
}
}
objects are string ids instead of objects
Mongoonse populate root object but not implicit deep populate
You can replace string by object as argument at populate method,
for provide full path to populate
const ViewedProfile = await User
.find({}, 'username friends profilePosts friendRequests')
.populate('friends')
.populate({
path: "profilePosts",
populate: [
{
path: "author",
// model: UserModel
},
{
path: "comments",
// model: ProfilePostCommentModel
},
{
path: "likes",
// model: UserModel
},
{
path: "hostProfile",
// model: UserModel
}
]
})
.populate('friendRequests');
You can see fully post at this problem.
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.
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?
I am a little stuck with trying to figure out the best way to populate a virtual schema in my db. In this instance, I want to check against multiple fields but I do not know any way to do this or alternative ways.
I had hoped I could just use some string arrays in the 'localField' & 'foreignField' keys of the virtual schema but this was not the case.
The user has a 'Series' _id saved, and the virtual schema 'leagues' gets all leagues that the user is entered into too, the catch is a league belongs to different Series. I want to only retrieve the leagues that the user is entered into & that match up with the user's series _id also...
As you can see currently this virtual schema just returns all the leagues the user is entered into regardless of the series. :(
Any ideas? I have been very confused about how to achieve this.
const schema: mongoose.Schema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
username: {
type: String,
unique: true,
},
series: {
ref: 'Serie',
type: mongoose.Schema.Types.ObjectId,
autopopulate: {
maxDepth: 1,
select: ['title']
}
}
});
schema.virtual('leagues', {
ref: 'League',
localField: '_id',
foreignField: 'users',
autopopulate: {
maxDepth: 1,
select: ['title', 'engineSize', 'host', 'series']
}
});
The league schema looks like this
const schema: mongoose.Schema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
title: String,
series: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Serie',
},
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}]
});
This was my solution to checking against multiple fields in mongoose using a getter.
schema.virtual('motoduel').get(function () {
return motoduelModel.findOne({
event: this.series.upcomingEvent._id,
riderGroup: this.riderGroup._id
});
});