How to make .populate exclude null values? - node.js

Is there a way to exclude lessons.lesson_id that are equal to null? I have the following from previous answers, but it's still giving lessons.lesson_id that are null
module.exports.getClasses = function(id, callback){
Class.findById(id)
.populate(
{path: 'lessons.lesson_id',
model: 'Lesson', $ne: null}
).exec(callback)
}
var classSchema = new Schema({
title: { type: String, required: true },
lessons: [{
_id: false,
lesson_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Lesson'}
}],
});
I'm trying to prevent the lesson_id with null from showing up
{ _id: 58090,
title: 'vcvc',
__v: 0,
lessons: [ { lesson_id: null }, { lesson_id: [Object] } ] }

So your ClassSchema is a touch off, I think you may find this will work better based on your requirements:
var classSchema = new Schema({
title: { type: String, required: true },
lessons: [{type: mongoose.Schema.Types.ObjectId, ref: 'Lesson'}],
});

Related

How to sort nested populated field in MongoDB (Mongoose)?

I am trying to sort populated array based on the nested and populated field using mongoose but it is not working.
Here are my modals.
const campaignSchema = new Schema(
{
name: { type: String, required: true },
prospects: [{ type: mongoose.Types.ObjectId, ref: "Prospect" }],
}
);
const prospectSchema = new Schema(
{
strategy: { type: String, trim: true },
contact: { type: mongoose.Types.ObjectId, ref: "Contact", required: true },
primaryCaller: { type: mongoose.Types.ObjectId, ref: "Contact" },
}
);
const contactSchema = new Schema(
{
firstName: { type: String, required: true },
lastName: { type: String, required: true },
}
);
Now I am trying to populate prospects and contact in each prospect in and sort them by contact.firstName using the following code.
const campaign = await Campaign.findOne({ _id: id }).populate({
path: "prospects",
populate: [
{ path: "contact", select: "firstName lastName" },
{ path: "primaryCaller", select: "firstName lastName" },
],
options: {
sort: "contact.firstName",
},
}).lean();
I tested it with sort: "strategy", and it is working fine with it.
I also tried Aggregations but it also didn't help.

I want to list users and all user's comments in MongoDB. Is it possible?

I want to list the users and search for comments in another collection using the same query.
That's my users Schema:
Schema({
cod: {
type: String,
require: true
},
name: {
type: String,
required: true
}
})
And that's my comments Schema:
Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
post: {
type: Schema.Types.ObjectId,
ref: 'posts'
},
comment: {
type: String,
required: true
}
})
I want get some like this:
{
_id: 5eee97c18b83e338bcbfa8f9,
name: 'Cool Name',
cod: 'CN001',
comments: [{
_id: ObjectId(...)
post: ObjectId(...),
comment: 'comment 1'
},
{
_id: ObjectId(...)
post: ObjectId(...),
comment: 'comment 2'
}
]
}
is it possible?
Thank you!
you might need to change your schema to:
Users:
Schema({
cod: {
type: String,
require: true
},
name: {
type: String,
required: true
},
comments: {
type: Schema.Types.ObjectId,
ref: 'comments'
}
})
Comments:
Schema({
post: {
type: Schema.Types.ObjectId,
ref: 'posts'
},
comment: {
type: String,
required: true
},
user: { // in case you want to query comments and populate the user
type: Schema.Types.ObjectId,
ref: 'users'
}
})
Then query:
users.findById({'your user id here'})
.populate({path:'comments',select:['post','comment']})
.then((response)=>{
// do anything you want with the data here
})

How can Mongoose Populate not working with Array of ObjectIds?

I'm trying to populate a mongoose query with an array of objectId field.
In another field with single objectId ref is working fine.
That's my "User" model:
const User = new Schema({
nome: {
type: String,
required: true
},
email: {
type:String,
required: true
}
})
mongoose.model('users',User)
That's my "Pedido" model:
const Schema = mongoose.Schema
const Pedido = new Schema({
id: {
type: String,
required: true
},
cliente: {
type: Schema.Types.ObjectId,
ref: 'clientes',
required: true
},
fotografos: {
type: [Schema.Types.ObjectId],
ref: 'users'
}
})
mongoose.model('pedidos',Pedido)
my router:
router.get('/pedidos',async(req,res)=>{
var query = await Pedido.find().populate('fotografos').populate('cliente').lean().exec()
console.log(query)
res.render("admin/pedidos",{pedidos: query})
})
That's the result in the console.log:
[
{
_id: 5e8e3bd16c57021f682b8e81,
fotografos: [],
cliente: {
_id: 5e8ccceea8a28146d86f4cac,
nome: 'Neymar',
email: 'neymar#ney.com',
__v: 0
},
__v: 0
}
]
fotografos field (array) are returning empty.
clientes field returns populated.
Can anybody help me with this?
You can use this code...
fotografos:[{
type: [Schema.Types.ObjectId],
ref: 'users'
}]
**Then do Populate**

How can I fetch data from more than one collections in Mongo using mongoose

How I can display details data of a profile when those data stored in more than one collections
tried this link
const profile = await userKushala
.find({_id: '5cd407c741f9e7373f10362c'})
.populate({
path: 'settingId',
populate : {
path : 'specialty',
populate : {
path: 'hospital_attached'
}
}
})
// First Collection(Basic Info.)
const userRegisterSchema = new Schema({
userType: {
type: String,
required: true
},
mobile: {
type: Number,
required: true,
unique: true
},
userId: {
type: String,
required: true
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
gender: {
type: String,
required: true
},
settingId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'providerSetting'
}
})
// Second Collection(Detailed Info.)
const serviceProfileUpdate = new Schema({
specialty :[{
type: mongoose.Schema.Types.ObjectId,
ref: 'specialtyMasterCsv'
}],
category: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'categoryMasterCsv'
}],
subscriptionPlan: {
type: mongoose.Schema.Types.ObjectId,
ref: 'planMasterCsv'
},
medicine: {
type : mongoose.Schema.Types.ObjectId,
ref: 'kushalaUser'
}
})
//Data in Mongo
{
"_id":{
"$oid":"5cd93ea6bd96e43664f49bf3"
},
"specialty":[
{
"$oid":"5cda85f26ffe60259a75ba17"
},
{
"$oid":"5cda85f26ffe60259a75ba18"
}
],
"category":[
{
"$oid":"5cda85f26ffe60259a75ba17"
},
{
"$oid":"5cda85f26ffe60259a75ba18"
}
],
"subscriptionPlan":{
"$oid":"5cda85f26ffe60259a75ba17"
},
"medicine":{
"$oid":"5cd407c741f9e7373f10362c"
},
"__v":{
"$numberInt":"0"
}
}
Expected Result will be from all the collections data should fetch but with the code I have it's giving the result till specialty but after that it's printing only ObjectID
This is what I have done and it's working still if anyone has a better solution, most welcome. Hope it helps someone.
const profile = await userKushala
.find({_id: '5cd407c741f9e7373f10362c'})
.populate({
path: 'settingId',
populate : {
path : 'specialty category subscriptionPlan medicine'
}
})
Try to populate like this:
.populate([
{path:'category',model:'categoryMasterCsv'},
{path:'subscriptionPlan',model:'planMasterCsv'},
{path:'medicine',model:'kushalaUser'}])
This is the method I use daily.

Node.js - mongoose. Cannot make a query on an ObjectId

This is my first time asking a question here.
I am using node.js and mongoose and I have the following three schemas:
var CustomerCouponSchema = new Schema({
coupon: { type: Schema.ObjectId, ref: 'Coupon' }
});
var CouponSchema = new Schema({
isActive: { type: Boolean, default: false },
supermarket: { type: Schema.ObjectId, ref: 'Supermarket' }
});
var SupermarketSchema = new Schema({
name: { type: string }
});
When I am trying to perform the following query:
//I have a variable named supermarketId which is an ObjectId
CustomerCoupon.find({ isUsed: false })
.populate({
path: 'coupon',
match: {
supermarket: { $or: [{ $eq: null }, { $eq: supermarketId }] },
isActive: true,
}
}).exec(function(err, data) {
});
I get the following error: Can't use $or with ObjectId.
Any help would be welcome

Resources