Mongoose populate method on query returns empty array - mongodb

I am having trouble querying my model, and using the .populate method to grab referenced documents of my object. Here are my schemas:
var userSchema = new Schema({
firstname: { type: String, required: true, unique: false },
lastname: { type: String, required: true, unique: false },
...
children: [{type: mongoose.Schema.Types.ObjectId, ref: 'Child'}],
});
var childSchema = new Schema({
firstname: { type: String, required: true, unique: false },
lastname: { type: String, required: true, unique: false },
...
legal_guardian_id: [{type: mongoose.Schema.Types.ObjectId, ref: 'User'}],
});
And here is how i'm trying to run my query:
User.findOne({ _id: '5b9d30083e33585cc0b8c710' })
.populate('children').exec((err, doc) => {
if (err) { return console.error(err); }
res.send(doc);
})
This results in "children": []
When I just use the findOne method and return the user, I get "children":["5b9d3f23d1408c5f4e2624f3"].
What am I doing wrong?

Related

mongoose validator not working as expected

i want to add batch,department,stream,id fields to the schema depending if usertype is “Student”,i do not understand why,but sometimes it adds the fields sometimes not.forexample if i created a user with usertype “Student” first it does not add the fields,but after that when i created a user with usertype “Teacher” or “Admin” it asks me the fields are required meaning it add the fields and this happens vice versa.why any way to fix this issue?please help guys.
what i have tried well,i have asked chatGpt but no answers i mean just the answers do not solve the issue.
here is the code
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
fullName: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
userType: {
type: String,
required: true,
},
phoneNumber: { type: String, required: true },
password: { type: String, required: true },
approved: { type: Boolean, default: true },
},
{
timestamps: true,
}
);
userSchema.pre("validate", function (next) {
if (this.userType === "Student") {
this.constructor.schema.add({
batch: {
type: Number,
required: true,
},
department: {
type: String,
required: true,
},
stream: {
type: String,
required: true,
},
id: { type: String, required: true }, //, unique: true
});
}
next();
});
const userModel = mongoose.model("users", userSchema);
module.exports = userModel;

Populate a property of a mongoose schema with all the data in another collection

I have a model with articles, and would like to populate an array of data with all the documents in a collection.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ArticlesSchema = new mongoose.Schema({
path: {
type: String,
required: true,
unique: true,
},
base_headline: {
type: String,
required: true,
},
intro: {
type: String,
required: true,
},
featured_image: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
platform_filter: {
type: String,
},
free_filter: {
type: String,
},
content_type: {
type: String,
required: true,
},
data: [{ type: Schema.Types.ObjectId, ref: 'DesignProducts' }],
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('Articles', ArticlesSchema);
The data property should be populated with all documents in the DesignProducts collection.
I tried running this but the data array is still empty:
Article.findOne({ path: slug }).populate('data').exec();
Here is what the designProducts model looks like:
const mongoose = require('mongoose');
const DesignProductsSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
intro: {
type: String,
required: true,
},
website: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('DesignProducts', DesignProductsSchema);
This array should be populated with all the documents in the DesignProducts collection:

find one with multiple conditions mongoose mongodb

I am trying to obtain data from mongodb. This is the scenario. Each user has a following property(array) that takes an array of users id.
The user model is as below
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
followers: [{ type: mongoose.Types.ObjectId, ref: "user" }],
following: [{ type: mongoose.Types.ObjectId, ref: "user" }],
});
in simple terms. I need to use two conditions where postedBy: { $in: req.user.following }, or postedBy:req.user._id
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
body: {
type: String,
required: true,
},
photo: {
type: String,
required: true,
},
likes: [{ type: mongoose.Schema.ObjectId, ref: "user" }],
comments: [
{
text: String,
postedBy: { type: mongoose.Schema.Types.ObjectId, ref: "user" },
},
],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
},
});
I have not figured out the second condition to add in the code below.
router.get("/getSubPost", requireLogin, async (req, res) => {
try {
const result = await Post.find({
postedBy: { $in: req.user.following },
})
.populate("postedBy", "-password")
.populate("comments.postedBy", "_id name");
res.json({ result });
} catch (error) {
console.log(error);
}
});

retrieving array data in mongodb which match id

Below is the schema. i want to get the answers as per matched qid, but i am getting all the answers in the answers array. i have tried almost all the queries but not able to understand why is this happening, if you could give link to other article that will be helpful too.
const id = req.params.id;
Channel.findOne({answer: {qid: {$in: [id]}}})
.then(result => {
console.log(result);
// let userAnswer;
// userAnswer = result.answer.map(i => {
// return {userId: i.userId , userName: i.userId.name, answer: i.answer}
// });
// res.json({ans: userAnswer, question: result.content});
})
.catch(err => {
console.log(err);
});
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const channelSchema = new Schema({
name: {
type: String,
required: true
},
category: {
type: String,
required: true
},
creator: {
type: String,
required: true
},
subscribers: [{type: mongoose.Types.ObjectId, required: true, ref: 'User'}],
content: {
question: [{
title: {type: String, required: true},
userId: {type: mongoose.Types.ObjectId, required: true, ref: 'User'}
}]
},
answer: [{
answer: {type: String, required: true},
qid: {type: mongoose.Types.ObjectId, required: true},
userId: {type: mongoose.Types.ObjectId, required: true, ref: 'User'}
}]
});
const model = mongoose.model('Channel', channelSchema);
module.exports = model;
const id = req.params.id;
return Channel.findOne({answer: {qid: {$in: [id]}}})
.then(snapshot => {
const results = [];
snapshot.forEach(doc => {
results.push({
id: doc.id,
data: doc.data()
});
});
return results;
})
})
.catch(err => {
console.log(err);
});
This is the way when you are going to fetch one array record. Not tested, only to show you how to get single record from collection

Mongoose Populate not returning related data

I have the following Models:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const imputerSchema = new mongoose.Schema({
dninie: {
type: String,
trim: true,
},
name: {
type: String,
trim: true,
required: true,
},
lastname: {
type: String,
trim: true,
required: true,
},
second_lastname: {
type: String,
trim: true,
},
phone : {
type: Number,
unique: true,
trim: true,
},
qr: {
type : String,
unique: true,
default: Date.now
}
});
module.exports = mongoose.model('Imputer', imputerSchema)
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const imputationSchema = new mongoose.Schema({
qr: {
type: String,
trim: true,
required: true,
ref: 'Imputer',
},
imputation_date: {
type: String,
default: Date.now,
required: true,
},
coordinates: {
type: [Number, Number],
index: '2d',
},
});
module.exports = mongoose.model('Imputation', imputationSchema);
and I trying to make a query like this:
Imputation.find()
.populate('imputer.qr')
.exec()
.then(docs => console.log(docs));
I also try
Imputation.find()
.populate('imputer')
.exec()
.then(docs => console.log(docs));
But I'm only got the documents on the imputation model without the field on the imputers model.
Here are some screenshots of how the documents look
Change your imputationSchema as follows:
const imputationSchema = new mongoose.Schema({
qr: {
type: mongoose.Types.ObjectId, ref: "Imputer",
trim: true,
required: true,
},
// other fields...
});
and then query like this:
Imputation.find()
.populate('qr')
.exec()
.then(docs => console.log(docs));