What is the process for incorporating additional keys into a Mongoose Schema?

Recently, I embarked on the journey of developing an app for my senior project that necessitates the integration of a database. After careful consideration, I opted for Mongoose due to its noSQL nature and relatively easier learning curve.

However, as progress continued, I encountered a roadblock - I couldn't quite grasp how to modify an existing Schema and incorporate new keys into it.

Take, for instance, this Schema which mirrors a post (think Tweets or Facebook updates) containing:

  • A string representing the content of the post
  • The user's ID who created the post
  • The date when the post was made

My current code snippet entails:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const PostsSchema = new Schema({
  Value: {
    type: String,
    required: true
  },
  User: {
    type: Schema.Types.ObjectId,
    ref:'users'
  },
  Date: {
    type: Date,
    default: Date.now
  }
});

// Establish collection and append schema
mongoose.model('posts', PostsSchema, 'posts');

What I aim to achieve now is to somehow access that schema and introduce a new key using a syntax akin to

PostsSchema.add({Private: { default: false}});

This implies that the schema in the database will appear as follows:

{
    "_id": {
        "$oid": "1831g98af21n9s5u7s9ccchj5"
    },
    "Value": "Beautiful day outside, can't wait to go jogging!",
    "User": {
        "$oid": "9a79ab143lbk9lk55wq327oi3226m"
    },
    "Date": {
        "$date": "2018-10-29T01:28:44.408Z"
    },
    "Private":  "false"
    "__v": 0
}

To circle back to my query - is there any way to accomplish this task? Alternatively, if you could point me towards documentation outlining similar methods, I would be extremely grateful. Thank you immensely!

Answer №1

To include a default value in the schema, simply add it like this:

const BlogSchema = new Schema({
  Title: {
    type: String,
    required: true
  },
  Author: {
    type: Schema.Types.ObjectId,
    ref:'authors'
  },
  PublishedAt: {
    type: Date,
    default: Date.now
  },
  IsPrivate: {type: Boolean, default: 'false'}
});

By setting a default value, any new record will automatically have this value assigned. Existing records without this field will also be updated with the default value when saved after adding the IsPrivate field.

If you require a more dynamic approach, consider using the Mixed Type with its advantages and disadvantages.

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

How can I find the week of the month using Moment.js? (similar to Google Calendar)

Currently leveraging the fantastic features of Moment.js, I am facing a dilemma. How can I determine which week of the month a particular date falls into? The documentation for Moment js only seems to provide information on "week of year." For instance, if ...

Attempting to utilize the findOne method in querying

Could use some assistance in figuring out what's going awry. I'm attempting to retrieve the latest ID recorded in my MongoDB collection. db.collection('task').findOne(({_id: new ObjectID}).sort('_id:: -1').limit(1), (error, t ...

Creating a PDF from HTML within an Ionic application

When trying to generate a PDF from an HTML page using the CORDOVA.PDF.GENERATOR plugin, I encountered an issue - the generated PDF lacked styling. Ideally, I want the PDF to mirror the style of the original HTML page. Is there a way to instruct the plugin ...

Utilizing jQuery AJAX to enable a functional back button feature upon modifying HTML

While there are numerous inquiries regarding jQuery and Back button issues, the focal point is typically on maintaining history features when using the browser back/forward buttons. One specific query I have is how to load an AJAX-affected HTML page when ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

What is the best way to turn my rectangular shape into a diamond in React Native using CSS?

https://i.sstatic.net/S4LPu.png Hi there, I'm facing a challenge with a project where my client wants to implement this orange border in react native. Unfortunately, CSS is not my strong suit. Can anyone please help me figure out how to achieve this ...

Creating translucent artwork using textured canvases in THREE.js

In my THREE.js application, I am creating 2D surfaces using PlaneGeometry and BasicMaterial meshes, while also supporting textures with a canvas: this.canvas = makeCanvas(canvasWidth, canvasHeight); this.ctx = this.canvas.getContext('2d'); this ...

What steps can I take to ensure that my popup images continue to appear?

Currently, I am working on creating a webpage that features thumbnails sourced from a local geoserver. The goal is to have these thumbnails expand into dialog windows that can be moved around. While I have successfully implemented the functionality to expa ...

JavaScript and AJAX: Dynamically Create URLs

I don't have any experience with web development, so could you please explain in detail? If my questions are unclear, feel free to ask for more information. Imagine I have a webpage with the following URL: www.mycompany.com/category1 This page has ...

Using Angular.js to Make a $http.get Request from a Different Controller

I am utilizing an HTTP resource that provides a JSON list of top 10 entities from a database by calling it in this manner: var filter= "john"; var myApp = angular.module('myApp', []); myApp.controller('SearchController', [&apo ...

Dividing the body of md-tabs in Angular material

My current project involves using angular material (https://material.angularjs.org/) I'm curious if there is a method to separate a tabs body from the tab list in angular material. Unfortunately, I couldn't find any information regarding this in ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

Understanding this JavaScript code involving shorthand if statements and commas can be achieved by breaking it down step by

Upon encountering this function within the codebase (which is compiled with webpack), my curiosity was piqued and I wanted to delve into its workings. Initially, my eyes fell upon t.length > 100. If it's greater than 100, then the next condition i ...

Is there a way to ensure my JavaScript code runs only once?

var startTime = '18:13'; var today = new Date(); var currentTime = today.getHours() + ":" + today.getMinutes(); var meetLink = 'https://meet.google.com/rnc-akmx-ubk'; if (currentTime == startTime) { joinMeeting(); } fun ...

Connect the mileage tracker to a Datalist or grid view component

I recently downloaded the Odometer Sample from , however, I am facing an issue where only the first element in the Datalist is getting the Odometer display, while others are not displaying it. Here is the snippet of code: <script type="text/javascript" ...

What is the best way to combine mongoose into an express.js project?

I've been diving into node.js to expand my skills in web development. While I grasp the concepts of express.js, I'm struggling with integrating mongoose models. Despite searching extensively online, I can't seem to find a solution. Should I ...

Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge. const example = { myFunction(){ console.log(this); }, myFunction2(){ function myFunction3(){ console.log(this) } return ...

Execute a function after another function completes in JQuery

After a page finishes refreshing, a jQuery event is triggered: $(#id).trigger('reloaded'); The 'reloaded' event is custom; How can I set up a listener to run another function when it's done 'reloading'? I had this ide ...

Styling the background position in CSS with the :target pseudo-class

After conducting some research, I was unable to find a satisfactory answer to my question. Essentially, I am attempting to shrink my website's header when a button is clicked. Here is the CSS code: I have been experimenting with making the backgrou ...

Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success. I attempted the following code but couldn't get it to update. The ng-chan ...