Standardizing MongoDB by excluding fields from documents

Struggling to display all fields when creating a new document in MongoDB, the current output is missing postTitle and postContent fields. Could this be due to an issue with the schema? The documentation is unclear.

https://i.sstatic.net/TWRbW.png

I have set up a basic Mongo DB like this:

const userSchema = new mongoose.Schema({

firstName: String,
lastName: String,
email: String,
hashPass: String,
userName: String,
isVerified: Boolean,

})

const postSchema = new mongoose.Schema({
    user: {type: mongoose.Schema.Types.ObjectId, ref:'User'},
    postDate: mongoose.Schema.Types.Date,
    postContent: String,
    postTitle: String,
    views: Number,
    likes: Number
})
const User = mongoose.model('User', userSchema)
const Post = mongoose.model('Post', userSchema)

Then I attempt to create a post by providing the user object ID:

const createPost = async ( postContent, postTitle, user) => {
const post = await new PostsDb({
    user,
    postDate: Date.now(),
    postContent,
    postTitle,
    views: 0,
    likes: 0
})
await post.save()

} 


 createPost( 'bla bla', 'title of post', '5ebab7d3351253283ca610dc')

Answer №1

When structuring your post scheme, it's important to include the user schema within the users.

const User = mongoose.model('User', userSchema)
const Post = mongoose.model('Post', userSchema)

The User Model corresponds to the userSchema and the post model is linked to the PostSchema.

I suggest making postTitle and postContent mandatory fields to avoid creating empty records.

const userSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    hashPass: String,
    userName: String,
    isVerified: Boolean,
})

const postSchema = new mongoose.Schema({
    user: {type: mongoose.Schema.Types.ObjectId, ref:'User'},
    postDate: mongoose.Schema.Types.Date,
    postContent: {
        type: String,
        required: true
        },
        postTitle: {
        type: String,
        required: true
        },
    views: Number,
    likes: Number
})
const User = mongoose.model('User', userSchema)
const Post = mongoose.model('Post', postSchema)

Additionally,

const post = new Post({
    user,
    postDate: Date.now(),
    postContent,
    postTitle,
    views: 0,
    likes: 0
})
await post.save()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to access the parent object within an event listener?

Is there a way to access the parent object (not window) within an event listener? Currently, I am able to get window using self, and the WebSocket object (which is the event listener target) using this. However, what I really want is to retrieve the Scrat ...

What is the best way to merge setInterval with mouseenter events?

I have successfully implemented code that refreshes a div using ajax. However, I am looking to add functionality so that the div only refreshes every 30 seconds when the tab is active. It seems that setInterval currently refreshes the div regardless of tab ...

Promises do not yield an array of objects

I am currently working on a project that involves using AngularJS with Firebase. In order to retrieve data from Firebase, I have implemented the following code snippets. Controller.js $scope.load_msg=function(){ $scope.msg=[]; Chat.load_msg($scope.na ...

What is the most effective way to share data among components in React?

I recently delved into learning about react and find myself puzzled on how to pass data between two components. Presently, I have set up 2 functions in the following manner: First, there's topbar.tsx which displays information for the top bar, inclu ...

Addressing the issue of audio files not being cached by IOS web browsers

I am currently developing a language learning website where users can listen to audio by clicking on objects. Many of the site's users are in remote areas with slow Internet connections, so I need to cache the audio files before each activity loads to ...

Guide on transforming 3D obj files into particles using three.js

I've been experimenting with particles in three.js, but I've encountered an issue when trying to convert an obj file (3D model) into particles. Here are the code snippets I've been working with, but so far all my attempts have failed. Does ...

Error: Attempting to access property 'email' from an undefined object was unsuccessful

I'm currently working on a Vue.js app with Laravel but I'm having trouble accessing the component from the object. What steps should I take? <script> import axios from 'axios'; export default { data : function (){ ret ...

Managing the grouping of values from an HTML form by key becomes a challenge when input fields can be dynamically added or removed

One interesting feature in my form is the ability to add and remove rows dynamically by clicking on a button. When multiple invoicerow elements are present, I want to group all results together for better organization. However, the array structure in the p ...

Dealing with functions that may not consistently return a promise

When dealing with a situation where a function does not always return a promise, how can it be best handled? The complexity of my current code prevents me from providing a detailed explanation, but essentially, the issue involves checking a condition and t ...

Attempting to loop through nested dictionaries within a pymongo database

I am currently facing a challenge in iterating over a MongoDB collection that contains nested subdictionaries. Within the structure of my collection, there is an object that holds other string values: For example: My goal is to retrieve the stats from t ...

Preventing unauthorized access and modification of a user's data in a Node.js application

In my mongoose schema, I am storing parking details along with a merchant id. A parking belongs to a specific merchant user and this field cannot be empty or null. Below is the model structure: const parkingSchema = new mongoose.Schema({ merchantId: { ...

Methods for maintaining accuracy when updating a user's follower count using Node.js with MongoDB

In my latest project, I am developing a social API system that allows users to follow and unfollow each other. The user model I currently have set up looks like this: sourceId: { type: Schema.Types.ObjectId, ref: "user", required: t ...

Is it possible to customize the color of the modal backdrop in layer v4 of the Material-UI library

I am struggling to modify the background color of an MUI V4 modal. Instead of getting a clean color, I am seeing a gray layer on top of the backdrop. Though this seems to be the default behavior, I want to remove it and target the shaded div directly rathe ...

Tips on showing a success notification following form submission in HTML

I have crafted this code utilizing a combination of bootstrap, python, and html. I have omitted the css portion for brevity, but I can certainly provide it if necessary. My aim is to be able to send an email using smtplib and flask, with the added function ...

Run code after all images have been rendered in vuejs

Is there a way to execute code after all images have loaded, specifically needing to set the scroll in a specific position? Using nextTick() processes the code before the images are loaded. The mounted and created methods can't be used since the code ...

Wordpress functionality for filtering Ajax posts using radio buttons

I am in the process of creating an Ajax post filter system using radio buttons to allow users to filter through multiple categories. Below is the code I have implemented: Front-end form: <form id="filter"> <?php if( ...

The never-ending loading problem at the bottom of the Firefox screen seems

I am facing an issue while trying to open something in Firefox using window.open(). The loading screen seems to never stop, and I cannot pinpoint the reason behind it. Any advice on how to resolve this would be greatly appreciated. View Screenshot: This ...

Angular Resolution Verification

I'm currently working on making HTTP calls in Angular and I want to trigger a different service function if an error occurs. The problem is, no matter what the original service call function returns, the promise always ends up being "undefined". Here& ...

Tips for efficiently reading a large volume of documents (1M+) from a collection in Cloud Firestore?

Encountering an error of 9 FAILED_PRECONDITION: The requested snapshot version is too old. const ref = db.collection('Collection'); const snapshot = await ref.get(); snapshot.forEach((doc,index) => { ...utilize data }) Want to retrieve all ...

What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class: class Box { constructor(x, y, width, height, frame, object_class, id) { this.x = x; this.y = y; ...