when I try to fetch all the post.user.name
it shows error like
Cannot read properties of undefined (reading 'name')
I just wanna display all the user in my node
Although user
is not null when I write like post.user
it shows me result like
{ _id: new ObjectId("632eab0e9b9ae6bbb44fce38"), email: '[email protected]', password: '1', name: 'sahil ', createdAt: 2022-09-24T07:00:30.925Z, updatedAt: 2022-09-24T07:00:30.925Z, __v: 0 }
In above name
is present
So why it show error when I do post.user.name
Below all the code
home.ejs->
<section id="feed-posts">
<h4>Posts</h4>
<% if (locals.user) { %>
<form action="/posts/create" id="new-post-form" method="POST">
<textarea name="content" cols="30" rows="3" placeholder="Type Here..."></textarea>
<input type="submit" value="Post">
</form>
<div id="posts-list-container">
<ul>
<% for(post of posts){ %>
<li>
<p>
<%= post.content %>
<br>
<small>
<%= post.user.name%>
</small>
</p>
</li>
<%} %>
</ul>
</div>
<% } %>
</section>
In above code post.content
and post.user
work fine but post.user.name
showing error. Although it contain name
.
index.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 8000;
const expressLayouts = require('express-ejs-layouts');
const db = require('./config/mongoose');
// used for session cookie
const session = require('express-session');
const passport = require('passport');
const passportLocal = require('./config/passport-local-strategy');
const MongoStore = require('connect-mongo')(session);
const sassMiddleware = require('node-sass-middleware');
app.use(sassMiddleware({
src: './assets/scss',
dest: './assets/css',
debug: true,
outputStyle: 'extended',
prefix: '/css'
}));
app.use(express.urlencoded());
app.use(cookieParser());
app.use(express.static('./assets'));
app.use(expressLayouts);
// extract style and scripts from sub pages into the layout
app.set('layout extractStyles', true);
app.set('layout extractScripts', true);
// set up the view engine
app.set('view engine', 'ejs');
app.set('views', './views');
// mongo store is used to store the session cookie in the db
app.use(session({
name: 'codeial',
// TODO change the secret before deployment in production mode
secret: 'blahsomething',
saveUninitialized: false,
resave: false,
cookie: {
maxAge: (1000 * 60 * 100)
},
store: new MongoStore(
{
mongooseConnection: db,
autoRemove: 'disabled'
},
function (err) {
console.log(err || 'connect-mongodb setup ok');
}
)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setAuthenticatedUser);
// use express router
app.use('/', require('./routes'));
app.listen(port, function (err) {
if (err) {
console.log(`Error in running the server: ${err}`);
}
console.log(`Server is running on port: ${port}`);
});
Controllers/home_controller.js
const Post = require('../models/post');
module.exports.home = function (req, res) {
// populate the user of each post
Post.find({}).populate('user').exec(function (err, posts) {
return res.render('home', {
title: "Codeial | Home",
posts: posts
});
})
}
controllers/posts_controller.js
const Post = require('../models/post')
module.exports.create = function (req, res) {
Post.create({
content: req.body.content,
user: req.user._id
}, function (err, post) {
if (err) { console.log('error in creating a post'); return; }
return res.redirect('back');
});
}
config/mongoose.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/codeial_development');
const db = mongoose.connection;
db.on('error', console.error.bind(console, "Error connecting to MongoDB"));
db.once('open', function () {
console.log('Connected to Database :: MongoDB');
});
module.exports = db;
models/post
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
content: {
type: String,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true
});
const Post = mongoose.model('Post', postSchema);
module.exports = Post;
models/user
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
name: {
type: String,
required: true
}
}, {
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User;
P.S:-
As per @Ogoh.cyril
when I log Post.find({}).populate('user').exec(function (err, posts) { console.log(posts)})
and instead of writing post.user.name
(which give error) I replace it with post.user
in my home.ejs
file.
I got the below output
[
{
_id: new ObjectId("63355014bd69c27e240429b7"),
content: 'hi mere bhai',
user: {
_id: new ObjectId("632eab0e9b9ae6bbb44fce38"),
email: '[email protected]',
password: '1',
name: 'sahil ',
createdAt: 2022-09-24T07:00:30.925Z,
updatedAt: 2022-09-24T07:00:30.925Z,
__v: 0
},
createdAt: 2022-09-29T07:58:12.104Z,
updatedAt: 2022-09-29T07:58:12.104Z,
__v: 0
},
{
_id: new ObjectId("63355047bd69c27e240429bf"),
content: '1st comment on that',
user: {
_id: new ObjectId("632eab0e9b9ae6bbb44fce38"),
email: '[email protected]',
password: '1',
name: 'sahil ',
createdAt: 2022-09-24T07:00:30.925Z,
updatedAt: 2022-09-24T07:00:30.925Z,
__v: 0
},
createdAt: 2022-09-29T07:59:03.972Z,
updatedAt: 2022-09-29T07:59:03.972Z,
__v: 0
}
]
Please help me......
CodePudding user response:
Update package -> connect-mongo
Then change the code of index.js
->
const MongoStore = require('connect-mongo');
store: MongoStore.create(
{
mongoUrl: 'mongodb://localhost/codeial_development',
mongooseConnection: db,
autoRemove: 'disabled'
}
It will work 100%
CodePudding user response:
Try adding optional chaining operator on user object, like so:
post.user?.name