简体   繁体   中英

How can I get a substring of the strings returned from a foreach loop in Node.js when connected to MongoDB Atlas

Problem: .substring() does not process when I connect my code to MongoDB Atlas.

Background: I'm new to coding and I am creating a blog where I need to render the posts to a blog route and to a dynamic route using route parameters and the posts need to be saved to a MongoDB Atlas server. I need to show only the first 100 characters in each post and then lead the user to another page using a "Read More" link. When I use localhost:3000 to render the data, the blog posts are successfully truncated using.substring(0, 100), but when I connect to MongoDB Atlas the error message "Cannot read property 'substring' of undefined." If I remove.substring() everything processes properly so is there another way of truncating the strings?

I couldn't find much online but so far I have tried MongoDB's $substrBytes and $substr(deprecated).

<% posts.forEach(function(post) { %>
    <!-- Render the postTitle value as the title of the journal entry -->
    <h2><%= post.title %> </h2>
    <p>
    <!-- Render the postBody value and truncate the blog post to 100 
    characters -->
    <%= post.content.substring(0, 100) + '...'%>
    <!-- Add a link to see the full blog post on a separate page -->
    <a href="/posts/<%= post._id %>">Read More</a>
    </p>
    <% }) %>

Expected results: ...Read More Actual results: TypeError:...\blog.ejs. Cannot read property 'substring' of undefined

Clearly some of your posts do not have content, Write the following safe code

<%= (post.content)? post.content.substring(0, 100) + '...' : 'No content available' %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM