Populate() specify multiple model - node.js

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

Related

How do I fetch User post on user timeline?

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;

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;

How to get a certain field of an embedded MongoDB document knowing its ObjectId

I have two collections in MongoDB database, Post and User. Each post contains the creator's ObjectId. When fetching all posts from the database, I want to add the name information, which is a field of User/creator. I tried to access the name field by post.creator.name, but it is not working.
const postSchema = new Schema(
{
title: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
imageUrl: {
type: String,
required: true,
},
creator: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
},
},
{ timestamps: true }
);
const userSchema = new Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
status: {
type: String,
required: true,
},
isExpert: {
type: Boolean,
required: true,
},
posts: [
{
type: Schema.Types.ObjectId,
ref: "Post",
},
],
});
exports.getPosts = (req, res, next) => {
Post.find({}).then((posts) => {
const postsWithAuthorName = posts.map(post => {
return {
...post,
name: post.creator.name
}
})
res.status(200).json({
posts: postsWithAuthorName,
});
});
};
Try this
Post.find({}).populate('creator', 'name')
See populate doc for reference.
When you query posts, creator is just an ObjectId, so you can't just call .name on it. To make it work you need to lookup this data by using e.g. populate.

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

Mongoose: query to get nested multiple related data

I'm new to NoSQL, in this case is MongoDB. I'm trying to make an API using ExpressJS and Mongoose. that have some data models
User.js
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
min: 3,
max: 50,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: Schema.Types.ObjectId,
ref: "Image",
},
}
Image.js
const ImageSchema = new mongoose.Schema(
{
desc: {
type: String,
},
url: {
type: String,
},
},
{ timestamps: true }
)
Post.js
const PostSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
desc: {
type: String,
max: 300,
required: true,
},
images: [
{
type: Schema.Types.ObjectId,
ref: "Image",
},
],
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment",
},
],
}
)
Comment.js
const CommentSchema = new mongoose.Schema(
{
user: {
type: Schema.Types.ObjectId,
ref: "User",
},
text: {
type: String,
required: true,
trim: true,
},
}
Now I want to perform a query that gets all comments based on specific postId. And the response data must include User data and image url that related to User. I tried this to get comment data
const comments = await Comment.find({post: req.params.postId}).populate("user")
It returned Comment with User data, but not include Image. How do I perform that query?
Try this (using the pupulate method with object configuration):
const comments = await Comment.find({post: req.params.postId}).populate({
path: 'user',
populate: {
path: 'profilePicture'
}
})
Here you can also select particular fields of each schema for example.
Let me know if it works for you.
Reference

Resources