Mongoose Object returns undefined when populating - javascript

I'm struggling with a little kinda of problem. What I wanna do is populating users in comments.
User schema:
const userSchema = mongoose.Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true
}
});
Comment schema:
const commentSchema = mongoose.Schema({
comment:{
type: String
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});
I had already created user and comment. Everything is fine when I'm trying to find both objects.
Comment:
Comment.find({}).exec((err, comments) => {
console.log(comments);
});
Output:
[
{
_id: 5e62472d5f593f3c642ee1e5,
comment: 'something',
user: 5e624522366d8c4150278a64,
__v: 0
}
]
User:
User.find({}).exec((err, users) => {
console.log(users);
});
Output:
[
{
_id: 5e624522366d8c4150278a64,
username: "SomeBodY",
password: "$2a$10$nm5BJ7zeI1tet3UEzcakf.8xoTgV/Yti5l1EKNg5inxiehevUlGRm"
}
]
The problem is when I'm using .populate('user') to Comment model it returns the comment as undefined in the console. I've tried different methods and even dropping the database but without success.
Here's the route when this happens
// Route To Single Project
router.get('/:projectId', (req, res) => {
const requestedProjectId = req.params.projectId;
Project.findById({_id: requestedProjectId}).populate('image_file').exec((err, project) => {
Rating.find({projectId: requestedProjectId}, (err, ratings) => {
Rating.countDocuments({projectId: requestedProjectId}, (err, count) => {
Comment.find({projectId: requestedProjectId}).populate('user').exec((err, comments) => {
console.log(comments)
if(err) return next(err);
res.render('project', { ... });
});
});
});
});
});

Actually your populate code is true.
The reason to get empty comments is because this Comment.find({projectId: requestedProjectId}) seems to return empty. So just check your request param.
Also to get rid of callback hell, you can rewrite your route using async/await like this.
router.get("/:projectId", async (req, res) => {
const requestedProjectId = req.params.projectId;
try {
const project = await Project.findById({ _id: requestedProjectId }).populate("image_file");
if (!project) {
return res.status(400).send("Project not found, check your projectId");
}
const comments = await Comment.find({ projectId: requestedProjectId }).populate("user");
console.log(comments);
const ratings = await Rating.find({ projectId: requestedProjectId });
const count = await Rating.countDocuments({ projectId: requestedProjectId });
res.render("project", {
project,
comments,
ratings,
count
});
} catch (err) {
console.log("Error: ", err);
res.status(500).send("Something went wrong");
}
});

Related

Express doesn't get another user with .map()

I came to a problem, where I can create conversations with multiple people 2 and so on. However, I can't understand why it doesn't store data to seperate User models.
Here is a code that you only need to know:
router.post(
"/",
auth,
[
check("conversators", "There should be at least two conversators").isLength(
{ min: 2 }
),
],
async (req, res) => {
const { conversators } = req.body;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
let conversation = new Conversation({
user: req.user.id,
conversators: conversators,
});
await conversators.map(async (conversator) => {
let user = await User.findById(conversator);
let newData = user;
newData.conversations.push(conversation.id);
console.log('Created data', newData);
let newUser = await User.findOneAndUpdate(
{ user: conversator },
{
$set: {
newData,
},
},
{ new: true }
);
await newUser.save();
console.log(newUser);
});
await conversation.save();
res.status(200).json(conversation);
} catch (error) {
console.error(error.message);
res.status(500).send("Server error.");
}
}
);
module.exports = router;
What I can assure is that this line: console.log('Created data', newData); prints the desired data. However, the next console: console.log(newUser); prints the same User model as the previous one.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
conversations: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "conversation",
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = User = mongoose.model("user", UserSchema);
The reason might be the difference in search methods used to get a record for newData and newUser. You have used User.findById for newData, which will obviously return different objects for different ids. But User.findOneAndUpdate uses filter criteria that may satisfy several results, but only first will be returned. So it boldly depends on what that user field is.
Here is the part that I changed and started to see the data on MongoDB:
await conversators.map(async (conversator) => {
let user = await User.findById(conversator);
let newData = user;
newData.conversations.push(conversation.id);
new Promise(async (resolve, reject) => {
user = await User.findOneAndUpdate(
{ id: conversator },
{
$set: {
newData,
},
},
{ new: true }
);
return resolve;
})
return await user.save();
});
Posted on behalf of the question asker

Remove document with references Mongoose

I'm having trouble removing Question when Survey gets deleted which is referenced in the Survey model. The survey gets deleted, but the question still remains in the database.
Survey Schema:
let surveyModel = mongoose.Schema(
{
Title: String,
Type: [String],
Questions: { type: mongoose.Schema.Types.ObjectId, ref: "questions" },
Answered: { type: Number, default: 0 }, // how many times users answered
DateCreated: { type: Date, default: Date.now }, // date created
Lifetime: { type: Date, default: Date.now }, // Survey expiry
User: { type: mongoose.Schema.Types.ObjectId, ref: "users" }
},
{
collection: "surveys",
}
);
Question Schema:
let questionModel = mongoose.Schema(
{
MC: {
QuestionText: String,
Options: [String],
},
TF: {
QuestionText: String,
Options: Boolean,
}
},
{
collection: "questions",
}
);
module.exports = mongoose.model("Question", questionModel);
Code I have right now:
// process survey delete
module.exports.processDeletion = (req, res, next) => {
let id = req.params.id;
Survey.remove({ _id: id }, (err) => {
Question.remove({_id: { $in: req.body.Questions }}, (err, res) => {
if (err) {
console.log(err);
res.end(err);
}
});
if (err) {
console.log(err);
res.end(err);
} else {
// refresh survey list
res.redirect("/live-surveys");
}
});
};
Your first step should be delete childrens, that is Question.
Note: i think "Questions" should be more of 1, then it must be an array of Reference in the Survey model. But, for this example it will to be as you have setted.
Then, your delete route, may to be some as:
router.delete("/delete/:surveyById", deleteSurvey");
router.param("surveyById", surveyId"); //This one is your middleware
//surveyController.js
const Survey = require("../models/Survey");
const Question = require("../models/Question");
exports.surveyId = (req, res, next, id) => {
Survey.findById(id).exec((err, data) => {
if(!data || err) return res.status(400).json({error: "Survey not found")};
else {
req.survey = data;
next();
}
)};
};
exports.deleteSurvey = (req, res) => {
Questions.findByIdAndRemove(req.survey.Questions) //Here your Questions Id
.exec((err, data)) => {
if(err) return res.status(400).json({error: "Error to delete questions"});
Survey.findByIdAndRemove(req.survey._id).exec((err, data) => {
if(err) return res.status(400).json({error: "Error to delete Survey"});
return res.json({ message: "Deleted")};
});
});
};
Also you can do with async await if you prefer, is the same, and you will have a better control about your code.

findOneandReplace keeps giving error: "Error: The replacement document must not contain atomic operators."?

I am currently developing a Pokemon Team Builder app with a React frontend and an Express backend with MongoDB for the database.
As far as I can tell my TeamSchema has no such atomic operators? Here is my TeamSchema:
const mongoose = require('mongoose');
const TeamSchema = new mongoose.Schema({
name: {
type: 'String',
required: true,
unique: true,
},
team: [
{
name: { type: String },
types: [{ type: String }],
sprite: { type: String },
},
],
username: {
type: String,
required: true,
},
userId: {
type: String,
required: true,
},
});
const TeamModel = mongoose.model('Team', TeamSchema);
module.exports = TeamModel;
And the error gets thrown in this method when I attempt to call the findOneAndReplace method by finding a team that has a name and userId match.
const replaceTeam = async (req, res) => {
const { teamName: name, filteredTeam: team } = req.body;
const { username, _id: userId } = req.user;
const newTeam = new Team({ name, team, username, userId });
try {
const replacedTeam = await Team.findOneAndReplace({ name, userId }, newTeam);
console.log(replacedTeam);
res.status(200).json({ message: 'Team was successfully overwritten!' });
} catch (err) {
console.log(err);
res.status(500).json({ message: 'An error occurred while updating the team.' });
}
};
This has been a real headscratcher here and I am not sure what is going wrong here. I have only started using mongoose a couple of weeks ago, so I wonder if it's something fundamental I am misunderstanding here.
The Mongoose function findOneAndReplace expects a document object passed in. See the below code.
details.findOneAndReplace(
{ location: "New York" },
{ name: "Sunny", age: 292, location: "Detroit" },
function(err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
}
);
Change
const newTeam = new Team({ name, team, username, userId })
to
const newTeam = {name, team, username, userId}
Also as in the other poster's code, add the new: true option to the call as follows by changing
const replacedTeam = await Team.findOneAndReplace({ name, userId }, newTeam);
to
const replacedTeam = await Team.findOneAndReplace({ name, userId }, newTeam, { new: true });
otherwise the original document will be returned into replacedTeam
You can just use findOneAndUpdate and update all the fields with new data. You can do it like this:
const replaceTeam = async (req, res) => {
const { teamName: name, filteredTeam: team } = req.body;
const { username, _id: userId } = req.user;
try {
const replacedTeam = await Team.findOneAndUpdate({ name, userId }, { name, team, username, userId }, {new: true});
console.log(replacedTeam);
res.status(200).json({ message: 'Team was successfully overwritten!' });
} catch (err) {
console.log(err);
res.status(500).json({ message: 'An error occurred while updating the team.' });
}
};

How could I reference a model to my User model with Express/Mongoose

I have two models, one being my User model and the other being my Course model. I would like to have it so when a User (Teacher) creates a course, it assigns that course to them and vice versa. Here are my models to explain better:
Course Schema/Model:
var CourseSchema = new Schema({
courseID: {
type: Number,
unique: true
},
courseName: String,
courseDesc: {
type: String,
default: "No course description provided."
},
coursePicture: {
type: String,
required: false
},
teacher: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
],
students: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Student'
}
]
})
User Schema/Model:
var UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
courses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Course'
}
],
password: String
});
Basically, I want to have it so on my frontend, I could do things like course.teacher.firstName or user.courses. My schemas are in two different files, but I believe that is fine. It's like assigning a user a post when they create it. I don't know how I could do this, as I've tried multiple things.
Right now, I currently have this for creating a course.
// Creates a new course
router.post('/create', function (req, res) {
Course.create({
courseID : req.body.courseID,
courseName : req.body.courseName,
courseDesc : req.body.courseDesc,
coursePicture : req.body.coursePicture,
teacher : req.body.id,
students: req.body.students
},
function (err, course) {
if (err) return res.status(500).send("There was a problem adding the information to the database.");
res.status(200).send(course);
});
});
I have already referenced the User model in the controller where that code ^ belongs as so var User = require('../user/User');
I believe that is needed to pull this off. If you have any questions, please let me know as I'm not the best at explaining things like this.
Hope someone can help me out!
Thanks.
// Creates a new course
router.post('/create', function (req, res) {
Course.create({
courseID : req.body.courseID,
courseName : req.body.courseName,
courseDesc : req.body.courseDesc,
coursePicture : req.body.coursePicture,
teacher : req.body.id, // find this user
students: req.body.students,
attendance: req.body.attendance
},
function (err, course) {
User.findById(req.body.id, function(err, user) {
user.update({
$push: {
courses: course._id
}
}, function(err) {
if (err) return res.status(500).send("There was a problem adding the information to the database.");
res.status(200).send(course);
})
})
});
});
This is an issue of database design. There should only be one place where information about a course is stored, the Courses table, and the Users table should know nothing about courses. There should be a table the relates a course to a user: a UserCourseRelations table.
I would strongly avoid the approach of storing an array of courseIds that a user is related in the user table as this is unnecessary coupling and so is not good database design. Also, it'll bog down reads to your Users table as those arrays grow on every row.
Here's how I would approach this. Note that some of this code uses ES6 syntax. The following code is untested, but should work. Take a look:
Create CourseSchema and CourseModel
var CourseSchema = new mongoose.Schema({
courseID: {
type: Number,
unique: true
},
courseName: String,
courseDesc: {
type: String,
default: "No course description provided."
},
teacherId: {
type: mongoose.Schema.Types.ObjectId,
}
coursePicture: {
type: String,
required: false
},
students: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Student'
}
]
})
CourseSchema.statics.createNew = function(data, callback) {
// do some verification here
// insert the new course
return new this(data).save((err, dbCourse) => {
if (err) {
return callback(err)
}
UserCourseRelationSchema.insertNew('teacher', userId, courseID, (err, dbUserCourseRelation) => {
if (err) {
return callback(err)
}
// done. return the new course
callback(null, dbCourse)
})
})
CourseSchema.statics.getByIds = function(courseIDs, callback) {
// find all of the courses where the courseID is in the courseIDs array
// see https://docs.mongodb.com/manual/reference/operator/query/in/
this.find({courseID: {$in: courseIDs}}, (err, courses) => {
if (err) {
// something went wrong
return callback(err)
}
callback(null, courses)
})
}
}
let CourseModel mongoose.model('courses', CourseSchema);
Create UserCourseRelationSchema and UserCourseRelationModel that relates a course to a user and vice versa
var UserCourseRelationSchema = new mongoose.Schema({
userId: {
type: String,
required: true,
},
courseID: {
type: Number,
required: true,
},
type: {
type: String,
enum: ['teacher', 'student'],
required: true,
},
});
UserCourseRelationSchema.statics.createNew = function(type, courseID, userId, callback) {
// do some verification here. I suggest making sure this relation doesn't already exist
// insert the new course
return new this({
courseID: courseID,
userId: userId,
type: type,
}).save((err, dbUserCourseRelation) => {
if (err) {
return callback(err)
}
// return the new relation
callback(null, dbRelation)
})
}
UserCourseRelationSchema.statics.getTeacherRelationCourseIdsByUserId = function(userId, callback) {
let query = this.find({userId: userId, type: 'teacher'})
query.distinct('courseID') // get an array of only the distinct courseIDs
query.exec((err, courseIDs) => {
if (err) {
// something went wrong
return callback(err)
}
callback(null, courseIDs)
})
}
let UserCourseRelationModel = mongoose.model('user_course_relations', UserCourseRelationSchema);
Create UserSchema and UserModel
var UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
password: String
});
UserSchema.statics.getAllCoursesById = function(userId, callback) {
// get the relations for the courses the user is a teacher of
UserCourseRelationModel.getTeacherRelationCourseIdsByUserId(userId, (err, courseIDs) => {
// get the courses by the returned coursIDs
CourseModel.getByIds(courseIDs, (err, courses) => {
if (err) {
// something went wrong
return callback(err)
}
callback(nul, courses)
})
})
}
let UserModel = mongoose.model('users', UserSchema);
// -- create the router
// Creates a new course
router.post('/create', function (req, res) {
CourseModel.createNew({
courseID : req.body.courseID,
courseName : req.body.courseName,
courseDesc : req.body.courseDesc,
coursePicture : req.body.coursePicture,
teacher : req.body.id,
students: req.body.students
}, function (err, course) {
if (err) return res.status(500).send("There was a problem adding the information to the database.");
res.status(200).send(course);
});
});
// -- done
I also suggest using promises if possible as it makes all of this logic much simpler.

Mongoose assign a collection to another

I am trying to add a post to a user collection after the user was created with empty posts. I have tried with populate with no success .. any help is much appreciated.
// Post Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
const UserModel = require('./user-model');
let PostSchema = new Schema({
author: {
ref: 'users',
type: Schema.Types.ObjectId
},
content: String,
description: String,
date: {
default: new Date(),
type: Date
},
title: String,
updatedAt: {
default: new Date(),
type: Date
}
});
let PostModel = mongoose.model('posts', PostSchema);
module.exports = PostModel;
// User Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
const PostModel = require('./post-model');
let UserSchema = new Schema({
name: {
type: String
},
email: {
lowercase: true,
type: String,
trim: true,
unique: true
},
password: {
type: String,
},
postList: [{
ref: 'posts',
type: Schema.Types.ObjectId
}],
});
const UserModel = mongoose.model('users', UserSchema);
module.exports = UserModel;
// save post controller
exports.savePost = (request, response, next) => {
let { author, description, title } = request.body;
let post = new PostModel({ author, description, title }).save();
UserModel.findById(author)
.then((user) => {
user.postList.push(post);
// Still Fails
// How can i assign the post to the user ?
});
}
Is there any way of doing this other then push or populate ?
To solve this problem I prefer to use $push of mongo
UserModel.findOneAndUpdate({
_id: author.id,
{
$push: {
postList: post
}
}
});
You need to follow this process to save successfully
Save post if success then
Update user to push postId in postlist
can try this one
exports.savePost = (request, response, next) => {
let post = new PostModel(request.body)
post.save(function(err, data) {
if(err) {
//return error
}
// check by console your author is present or not
// let author in your req.body
let author = req.body.author
UserModel.findOneAndUpdate({_id: author},{$push: {postList: post._id}},{new:true} function(error, user) {
if(error) {
// return error
}
console.log(user)
// return success
})
});
}
exports.savePost = (request, response, next) => {
let { user, description, title } = request.body;
let post = new PostModel({ user, description, title });
post.save()
.catch((error) => {
if (error)
throw new Error(error);
})
.then((post) => {
UserModel.findOneAndUpdate({ _id: user }, {$push: { postList: post._id } })
.populate('postList')
.catch((error) => {
if (error)
throw new Error(error);
})
.then((user) => {
user.postList.forEach((item, postion) => {
console.log(`${item} -at ${postion} \n`);
});
});
});
}
This is what i did and it worked after all. I don't know if this is the correct solution but this is working.

Categories