How to fill multiple models with mongodb using "population" - javascript

I am trying to display all the data with the "populate" statement. But I only get one "populate" but when I put many it doesn't work.
what I want to do is to bring me the data from the "User", "Customer" model as well.
This is my code
My Model:
import { model, Schema } from 'mongoose';
const RoomSchema = new Schema({
Users: [
{
agentId: {
type: Schema.Types.ObjectId,
ref: "User",
required: false,
},
customerId: {
type: Schema.Types.ObjectId,
ref: "Customer",
required: false,
},
typeId: Number, // 1 - agent, 2 - client
},
],
Messages: [
{
agentId: {
type: Schema.Types.ObjectId,
ref: "User",
required: false,
},
customerId: {
type: Schema.Types.ObjectId,
ref: "Customer",
required: false,
},
message: {
type: String,
required: true,
},
date: Date,
sender: Number,
},
],
FinishAt: Date,
FinishBy: String,
typeFinishBy: Number, // 1 - agent, 2 - client
}, {
timestamps: true,
versionKey: false
});
export default model('Room', RoomSchema);
this is the sentence I am using
import Room from "../models/Room.js";
async function getOnlyRoom(id) {
const foundRoom = await Room.findById(id)
.populate('Users.agentId')
.populate('Users.customerId')
.populate('Messages.agentId')
.populate('Messages.customerId')
.execPopulate();
return foundRoom
}
Image of Json Postman
only works with one
foundRoom.populate('Users.customerId')
Works with only populate
this is the error
image of error
Thank you very much for your help

I have found the solution to my problem
I was researching the solution on the mongoose website and did it with a single populate.
const populateRoom = await foundRoom
.populate([
{ path: 'Users.agentId', select: 'name' },
{ path: 'Users.customerId', select: 'name' },
{ path: 'Messages.agentId', select: 'name' },
{ path: 'Messages.customerId', select: 'name' }
])
return populateRoom;

Related

how to populate following documents

I have two mongoose db schemas as follows
Posts schema
return model('post',
Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
createdBy: {
type: Types.ObjectId,
ref:"user"
},
},
{ timestamps: true })
);
Like schema
return model('like',
Schema({
userId: {
type: Types.ObjectId,
required: true,
ref: "user"
},
postId: {
type: Types.ObjectId,
required: true,
ref: "post"
}
},
{ timestamps: true })
);
how to populate like documents with post documents?i also want to consider the case where a post not have a like schema at all.

How to populate all the user fields which is inside an object inside of an array and another array in mongoose

here is my course schema
const CourseSchema = new Schema(
{
courseName: {
type: String,
required: true,
lowercase: true,
},
comments: [
[
{
user: {
type: Schema.Types.ObjectId,
ref: "Users",
required: true,
},
comment: {
type: String,
required: true,
},
createdAt: {
type: Date,
required: true,
},
},
],
],
},
{
timestamps: true,
}
);
const Course = mongoose.model("Course", CourseSchema);
I want to populate the user field. I've tried many stack overflow solutions but none of them works for me.
I populated the model like this but, doing so it only populates the first index the of every model.
courses = await Course.findOne({}).populate({
path: "comments.0.0.user",
});
You can populate another level deeper, here's what you need to do:
db.Course.findOne({}).populate({"path":"comments",populate:[{
path:"user",
model:"Users"
}]})
Another way of nested populating data:
db.Course.findOne({}).populate("comments.user")

Mongoose getting the error: MissingSchemaError: Schema hasn't been registered for model

I am getting this error and can't figure it out. I HAVE NAMED THE REF EXACLTY AS THE MODEL:
MissingSchemaError: Schema hasn't been registered for model "ParticipantStatus".
Here are my models:
ParticipantStatus model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const participantStatusSchema = new Schema({
_id: {
type: Number,
required: true,
},
name: {
type: String,
required: true,
},
});
module.exports = mongoose.model('ParticipantStatus', participantStatusSchema);
EventParticipant model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventParticipantSchema = new Schema(
{
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
eventId: {
type: Schema.Types.ObjectId,
ref: 'Event',
required: true,
},
teamId: {
type: Schema.Types.ObjectId,
ref: 'Team',
},
statusId: {
type: Number,
ref: 'ParticipantStatus',
required: true,
},
isActive: {
type: Boolean,
required: true,
default: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model('EventParticipant', eventParticipantSchema);
This is the code where the error is thrown, when i try to get event participants and populate statusId(ParticipantStatus):
let participants = await EventParticipant.find(
{
eventId: req.params.eventId,
isActive: true,
},
{ _id: false }
)
.populate('userId', 'email')
.populate('statusId')
.select('userId');
I have been stuck for hours on this. Only the .populate('statusId') part throws the error, the rest works well. Thanks in advance
type of field that you want to populate based on should be ObjectId so change the type of statusId from Number to Schema.Types.ObjectId like this:
statusId: {
type: Schema.Types.ObjectId,
ref: 'ParticipantStatus',
required: true,
}
Well the problem was that u need to import:
const ParticipantStatus = require('../models/participantStatus.model');
even if you do not REFERENCE IT DIRECTLY in your code, which is really strange in my opinion.
Hope this helps anyone.

How to unbind nested objects, result of an one to many relationship with aggregate mongo

I need help with mongo, I need to make a query resulting in a objext and many object nested resulting of a one to many relation ship of these schemas:
const ProductSchema = new Schema({
name: { type: String, required: true, unique:true },
picture: { type: String },
description: { type: String, required: true },
isEnabled: { type: Boolean, required: true },
brand: { type: Schema.Types.ObjectId, ref:'Brand' },
slug: { type: String, required: true },
category: { type: mongoose.Schema.Types.ObjectId, ref:'Category' },
reviews: [{ type: mongoose.Schema.Types.ObjectId, ref:'Review' }]
const PackageSchema = new Schema({
type: { type: String, enum:["WEIGHT", "EACH"], required: true },
value: { type: Number, required: true },
price: { type: Number, required: true },
stock: { type: Boolean, required: true},
description: { type: String, required: true},
product: { type: mongoose.Schema.Types.ObjectId, ref:'Product', required: true },
dispensary: { type: mongoose.Schema.Types.ObjectId, ref:'Dispensary', required: true }
This is the code i made
const dispensaryID;
payload = _thisModel.aggregate([
{
$lookup:{
from: "packages",
localField:'_id',
foreignField:'product',
as:"package"
}
},
{"$unwind": {path:"$package", preserveNullAndEmptyArrays: true}} ,
{
$group:
{
_id:"$_id",
number: {
$sum: "$package"
},
package: {$push: '$package'},
}
},
],(aggErr, aggResult) => {
(aggErr) ? console.log(aggResult)
: console.log(aggResult)
})
Buy it is resulting on this:
{ _id: 5ebf98724ef6e503ccd7ae4f, clicks: 0, package: [ [Object] ] },
{
_id: 5ebf98614ef6e503ccd7ae4e,
clicks: 0,
package: [ [Object], [Object], [Object], [Object] ]
},
{ _id: 5ebed37b52ec0043fca22893, clicks: 0, package: [] }
So i need to unbind those objects, I need to see the packages details instead some "[Object]", I tried reconfiguring the script but this is the nearest result I got, also I need to check if a dispensary: { type: mongoose.Schema.Types.ObjectId, ref:'Dispensary', required: true } given in the second schema exists in any of those packages, I will give a const to check if it maches, and add a prop says exists: true on the product object or only delete the whole product object with the packages.
Thanks for the help

Handlebars each statement can access data that handlebars won't access directly

I have a simple help desk app I've been building, where user can make request for site changes. One of the features is being able to see all request made by a specific person, which is working. However on that page I wanted to have something akin to "User's Request" where user is the person's page you are on. However I can't seem to get it to work without some weird issues. If I use:
{{#each request}}
{{user.firstName}}'s Request
{{/each}}
It works but I end up with the header being written as many times as the user has request. However, when I tried:
{{request.user.firstName}}
It returns nothing.
My route is populating user data, so I think I should be able to reference it directly. Here's the route:
// list Request by User
router.get('/user/:userId', (req, res) => {
Request.find({user: req.params.userId})
.populate('user')
.populate('request')
.then(request => {
res.render('request/user', {
request: request,
});
});
});
Here's the schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const RequestSchema = new Schema({
title: {
type: String,
required: true,
},
body: {
type: String,
required: true,
},
status: {
type: String,
default: 'new',
},
priority: {
type: String,
default: 'low',
},
project: {
type: String,
default: 'miscellaneous',
},
category: {
type: String,
default: 'change',
category: ['change', 'bug', 'enhancement', 'investigation', 'minor_task', 'major_task', 'question'],
},
organization: {
type: String,
default: 'any',
},
assignedUser: {
type: String,
default: 'venkat',
},
allowComments: {
type: Boolean,
default: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
lastUser: {
type: Schema.Types.ObjectId,
ref: 'users',
},
date: {
type: Date,
default: Date.now,
},
lastUpdate: {
type: Date,
default: Date.now,
},
comments: [{
commentBody: {
type: String,
required: true,
},
commentDate: {
type: Date,
default: Date.now,
},
commentUser: {
type: Schema.Types.ObjectId,
ref: 'users',
},
}],
});
// Create collection and add Schema
mongoose.model('request', RequestSchema);
The rest of the code is at: https://github.com/Abourass/avm_req_desk
If anyone is wondering how, the answer was to add the array identifier to the dot path notation:
<h4>{{request.0.user.firstName}}'s Request</h4>

Categories

Resources