What causes an error when attempting to add a new user to the database?

Currently, I am delving into the world of Mongodb. To kick things off, I initiated by executing npm install --save mongoose uuid within the confines of Terminal. The primary objective of my project revolves around storing user information in the database.

Post running node index.js in Terminal, my expectation is to witness:

About to save!
Saved!

Unfortunately, what greets me in Terminal is (shown below):

This is the content of index.js:

var mongoose = require('mongoose');
var uuid = require('uuid');

var Schema = mongoose.Schema;


/* Novel code from recommended source with an error */ 

var promise = mongoose.connect('mongodb://localhost:testMongo/testMongo', {
    useMongoClient: true,
});

promise.then(function(db) {

    db.model();
    connection.openUri('mongodb://localhost:testMongo/testMongo', { /* options */ });


var userSchema = new Schema({
    email: {
        type: String,
        unique: true
    },
    password: {type: String},

    todos: [
        {
            text: {type: String}
        }
    ]
});

userSchema.pre('save', function(next) {
    console.log("About to save!");
    var user = this;
    user.password = uuid.v4();
    next();
});

 var User = mongoose.model('user', userSchema);
 var email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9febfaecebdfebfaecebb1fcf0f2">[email protected]</a>';

// var user = new User({
//     email: email
// });
//
// user.save(function(err) {
//     if(err) {
//         return console.log(err);
//     } else {
//         return console.log("User was saved!");
//     }
// })
//
// console.log("Outside of callback!");

var text = "This is a todo.";

User.findOne({email: email}, function(user, err) {
   if(err) {
       return console.log(err);
   }

   if(!user) {
       return console.log("Couldn't find user!");
   }

   var count = user.todos.push({
       text: text
   });

   console.log(count);

   user.save(function(err){
      if(err) {
          console.log(err);
      } else {
          console.log("Saved!");
      }
   });
});

An error shown in Terminal:

(node:14312) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
{ _id: 595fe7c14a9810330c75aacc,
  password: '297d5907-d9d7-49ef-800c-97a56aa395f7',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e591809691a591809691cb868a88">[email protected]</a>',
  __v: 0,
  todos: [] }
  

Answer №1

It's important to note that the message in question is not indicating an error, but rather a warning identified as DeprecationWarning. Additionally, within the message provided, there is a helpful link included for resolving this warning: http://mongoosejs.com/docs/connections.html#use-mongo-client

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

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

I'm not satisfied with the value of the ReactJs state after the change

I am working on creating a calendar app for practice purposes. Currently, I have a current_month state variable set to 1. Additionally, I have a function called IncreaseMonth() that is designed to increment the value of current_month. However, when the va ...

Tips on avoiding blurring when making an autocomplete selection

I am currently working on a project to develop an asset tracker that showcases assets in a table format. One of the features I am implementing is the ability for users to check out assets and have an input field populated with the name of the person author ...

Unable to access ng-model values within ng-repeat loop

I'm having trouble setting ng-model values within an ng-repeat statement. When I repeat this div with an array of JSON objects, I am able to print the 'ID' value of the object in any element. However, I can't use that as the ng-model v ...

Craft a Flawlessly Repeating Sound Experience - Online

I'm facing a challenge in creating a flawless loop of an audio file. However, all the methods I've tried so far have resulted in a noticeable gap between the end and the start. Here are the approaches I experimented with: The first approach inv ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Displaying asynchronous promises with function components

Apologies if this post appears duplicated, I am simply searching for examples related to class components. Here is the code snippet I am working with: export const getUniPrice = async () => { const pair = await Uniswap.Fetcher.fetchPairDat ...

How can you effectively retrieve values in Chakra Core without encountering any memory complications?

I have been studying this example in an effort to develop a basic JavaScript engine that can execute scripts like the zxcvbn library. I thought I had it all figured out, but there are certain parts of the code that still puzzle me. Particularly, I am strug ...

Simplified user interface for detecting radio button clicks

Currently working on a form that includes radio buttons, where an update function is triggered whenever there is a user input change. The challenge I am facing is how to incorporate user-friendly radio buttons with a larger button area encompassing both t ...

AngularJS seems to be ignoring CSS styles when displaying list items in the ng-repeat loop

After coming across a tutorial on creating round circles connected by a line in CSS, I decided to implement it myself. Interestingly, everything worked perfectly fine when I tested it with static HTML. However, when I tried to make it dynamic using Angular ...

What is the best way to populate a select input field with options using JavaScript?

When I am loading an HTML table, there is a select input field that needs to display some options. Immediately after constructing the HTML table row, I invoke a function to populate this input field using its class. Below is the relevant HTML snippet and ...

Waiting for a React ref to become available after being rendered in a separate container: A guide

Revised: clearer explanation The scenario: A plain HTML code is received from a third-party server, with the intention to embed in a React application make modifications to it The traditional JavaScript approach The string can be modified using reg ...

A server that broadcasts using Javascript, Node.js, and Socket.IO

Could someone provide a simple example of how to create a Node.JS server that runs both a TCP and Socket.IO server? The main goal is to pass data from a TCP client to multiple Socket.IO clients who are interested in it. This setup is intended to facilita ...

What is the method to determine the size of a file in Node.js?

Have you ever wondered how to accurately determine the size of a file uploaded by a user? Well, I have an app that can do just that. The code for this innovative tool is provided below: Here is the snippet from server.js: var express = require('expr ...

Tips for triggering several functions with a single onClick event in React?

I am currently working on a React Project where I have defined several functions to set conditions for rendering components on the page. However, I now need to be able to call all these functions again within the components when a button is clicked, in ord ...

Need a jQuery function that updates the 'id' after clicking on a specific div? Here's how to do it!

I need help simplifying my current situation. Step 1: I want to increment the variable "count" by 1 every time a specific div is clicked. Step 2: After updating "count", I want to utilize it in another function. This function involves copying the value f ...

The feature of Time to Live (TTL) is not supported by sails-m

attributes : { username : { type: "string",required:true,unique:true }, password : { type : "string",required:true}, email : { type : "string",required:true,unique:true}, expireAt : { type:'date','defaultsTo':Date ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

"Implementing a sorting feature in a product filtering system with JavaScript/Vue, allowing

I have a dataset structured like this: > Price : ["800000","989000","780000","349000"] If the user selects 'sort by lowest price', I want the data to be arranged from the lowest price to the highest price as follows: > Price : ["349000" ...