I am working on a blog app. Here one user has a one-to-many relationship with posts.After creating the basic CRUD I wanted to make a profile page featuring all the posts of a single User. I am following all the steps but still when I fetch all users I get empty array of Post.
And also I am trying to get user name in each post instead of only ID. I am using Populate but still getting only user id back.
router.get('/', auth, async (req, res) => {
try {
const Posts = await Post.find()
.sort({
date: -1
})
.populate('users');
res.json(Posts);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
Here's my user schema
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
],
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
Here's Post Schema
const mongoose = require('mongoose');
const PostSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const Post = mongoose.model('post', PostSchema);
module.exports = Post;
I am following all the steps but still when I fetch all users I get empty array of Post
When you add a new post you must also update the posts field of the userSchema:
const newPost = await Post.insert(/* post */);
await User.findOneAndUpdate({ _id: newPost.user }, { $push: { posts: newPost._id }, { new: true });
And also I am trying to get user name in each post instead of only ID. I am using Populate but still getting only user id back
Try .populate('user'); without s
Related
This question already has answers here:
How to avoid 'cannot read property of undefined' errors?
(18 answers)
Closed 1 year ago.
I'm trying to access Dashboard but I'm getting an error.
TypeError: Cannot read property 'id' of undefined
I have created a route to access DASHBOARD using Express Router. ('routes/index')
const express = require('express')
const router = express.Router()
const User = require('../models/User')
router.get("/dashboard", async (req, res) => {
try {
const users = await User.find({ user: req.user.id }).lean() //This line is generating the error
res.render("dashboard", {
name: req.user.name,
users
});
} catch (err) {
console.log(err);
res.render('error/500')
}
})
module.exports = router
I have added this route in my app.js file
app.use('/',require('./routes/index'))
This is my MongoDB Database Schema ('models/User')
const mongoose =require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required:true
},
email: {
type: String,
required:true,
unique:true
},
password: {
type: String,
required:true
},
confirmpassword: {
type: String,
required:true
},
tokens: [{
token: {
type: String,
required: true
}
}],
role: {
type: String,
required:true
},
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('User', UserSchema);
I have successfully registered and saved a user in my database
[Database Entry][1]
So error is because, your id is not define.
Please console.log(req.user) or console.log(req.body), you will know what you are getting.
Request doesn't include user object. You should get empty array when console.log(req.body).
You can do like this:
req.user = await User.findById(yourdata.id)
Then you can use req.user.id
I am trying to read data from the mongo database , but I am getting error.
I will explain what I did.
create two schema
let CompanySchema = new Schema({
name: {type: String, required: true, max: 100},
contactPerson: {type: String},
});
// Export the model
module.exports = mongoose.model('Company', CompanySchema);
let UserSchema = new Schema({
name: {type: String, required: true, max: 100},
companyId:{ type: Schema.Types.ObjectId, ref: 'companyId' }
});
// Export the model
module.exports = mongoose.model('UserTest', UserSchema);
First, add one company like this.which is successfully added
app.get('/addCompany', async (req, res) => {
let company = new Company({
name: 'Test 1',
contactPerson: 'rajesh'
})
company.save(function (err) {
if (err) {
console.log(err);
res.status(500).send(err);
// return next(err);
}
res.send('company added successfully')
//res.render('index', { title: 'Express'})
});
})
Then I added a user like this .which is successfully added.
app.get('/addUser', async (req, res) => {
let user = new User({
name: 'Test 1',
companyId: '5d3d46b2825d7f0eaf9d9d27'
})
user.save(function (err) {
if (err) {
console.log(err);
res.status(500).send(err);
// return next(err);
}
res.send('user added successfully')
//res.render('index', { title: 'Express'})
});
})
Now I am trying to fetch all user with company detail and getting error
app.get('/getUser', async (req, res) => {
User
.find({})
.populate('companyId') // only works if we pushed refs to person.eventsAttended
.exec(function(err, data) {
if (err) {
console.log(err)
return;
}
res.send(data);
});
})
error
MissingSchemaError: Schema hasn't been registered for model "companyId".
Use mongoose.model(name, schema)
at new MissingSchemaError (/Users/b0207296/WebstormProjects/untitled2/node_modules/mongoose/lib/error/missingSchema.js:22:11)
at NativeConnection.Connection.mode
Can you try now after changing your second schema to this :
let UserSchema = new Schema({
name: {type: String, required: true, max: 100},
companyId:{ type: Schema.Types.ObjectId, ref: 'Company' }
});
module.exports = mongoose.model('UserTest', UserSchema);
Assuming companyId's has matching documents in _id's of Company. Similar kind of functionality can also be achieved thru $lookup of mongoDB.
in ref you should pass the Company instead of company id
let UserSchema = new Schema({
name: {type: String, required: true, max: 100},
companyId:{ type: Schema.Types.ObjectId, ref: 'Company' }
});
I'm working on API project for client.
The problem is using POSTMAN when i hit POST method the status I get is Status: 500 TypeError.
I tried put some data to my DATABASE manually so that I can check if my CRUD method is working. The GET method is working fine.
This is the API route i created:
const express = require('express')
const Client = require('../../models/Client')
const router = express.Router()
// Get Client
router.get('/', (req, res) => {
Client.find()
.sort({date: -1})
.then(clients => res.json(clients))
.catch(err => res.status(404).json(err))
})
// Create Client
router
.post('/', (req, res) => {
const newClient = new Client({
name: req.body.name,
email: req.body.email,
phone: req.body.phone,
})
newClient
.save()
.then(client => res.json(client))
.catch(err => console.log(err))
})
module.exports = router
This is my Model:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ClientSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
created_at: {
type: Date,
default: Date.now
},
updated_at: {
type: Date,
default: Date.now
},
})
module.exports = Client = mongoose.model("client", ClientSchema);
ERROR Message: Cannot read property 'name' of undefined.
I tried all I can do, changing some code, hard coded some fields, but nothing works.
How to fix the error I get?
In my program I want to populate my index page with a model called a group. Previously I just showed all the groups that existed in the database, but now I want to only show the groups that the user who is logged in is associated with.
Here are the models:
Group Model
var mongoose = require("mongoose");
var groupSchema = new mongoose.Schema({
name: String,
thumbnail: String,
description: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
inviteCode: String,
images: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Image"
}
],
users: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
] });
module.exports = mongoose.model("Group", groupSchema);
User Model
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
groups:
[
{
type: mongoose.Schema.Types.ObjectId, //referencing model by id
ref: "Group" //name of the model
}
],
images:
[
{
type: mongoose.Schema.Types.ObjectId, //referencing model by id
ref: "Image" //name of the model
}
]
});
UserSchema.plugin(passportLocalMongoose); //add in local mongoose methods to user
module.exports = mongoose.model("User", UserSchema);
My Index Route:
//Index Route
router.get("/", middleware.isLoggedIn, function(req, res){
var user = req.user;
user.populate("groups").exec(function(err, allGroups){
if(err){
console.log(err);
} else {
res.render("groups/show", {groups: allGroups});
console.log(allGroups);
}
});
});
And this is the error I get:
TypeError: user.populate(...).exec is not a function
I am not sure why I cant use the populate method with my user model, can someone explain me an alternative to achieve the desired outcome. Thank you.
I think the problem is that req.user is not a schema, so .populate is not a method carried by that variable in its object prototype. Hence the terminal telling you it's not a function.
You have to require the User schema like this in your index route:
const User = require("./models/user");
Then find the user by its id then populate it:
//Index Route
router.get("/", middleware.isLoggedIn, function(req, res){
var user = req.user;
User.findById(req.user._id, function(err, foundUser) {
let user = foundUser;
user.populate("groups").exec(function(err, allGroups){
if(err){
console.log(err);
} else {
res.render("groups/show", {groups: allGroups});
console.log(allGroups);
}
});
});
});
Let me know if it works!
var CommentsSchema = new mongoose.Schema({
created: Date,
user: {type: mongoose.Schema.Types.ObjectId, ref: "User"},
body: String,
news: {type: mongoose.Schema.Types.ObjectId, ref: 'Newsletter'},
reply: [{ **//I want to populate the user into reply array**
user: {type: mongoose.Schema.Types.ObjectId, ref: "User"},
body: String,
created: Date
}]
});
I'm populating my comments and I also want to populate the user on every index of the reply array. Would I have to do it on the same post call or a different post call?
router.post('/reply', auth, function(req, res) {
var reply = req.body;
reply.created = new Date();
reply.user = req.payload.id;
console.log(reply);
Comment.update({_id: reply.comment}, {$push: {reply: reply}})
.populate({
path: 'user',
model: 'User',
select: 'username name facebook.photo images'
})
.populate({
path: 'reply',
model: 'user',
select: 'username name facebook.photo images'
})
.exec(function(err, result) {
if(err) return res.status(500).send({err: "Issues with server, re: reply"});
if(!result) return res.status(400).send({err: "Could not post reply"});
res.send(reply);
})
})