Store and Persist Data for a Model in MongoDB

Currently working through the MongoDB and Mongoose section on FreeCodeCamp.

The challenge involves creating a document instance using the Person constructor previously built. The object passed to the constructor should have fields for name, age, and favoriteFoods that comply with the types in the Person Schema. Then, call the document.save() method on the returned document instance and provide a callback following the Node convention.

I've set up the person schema and constructor, but I'm unsure about what's missing and how to properly put it all together to solve the problem. Can anyone offer clarification?

var mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI);

var Schema = mongoose.Schema;

var personSchema = new Schema({
  name:  {
    type: String,
    required: true
  },
  age: Number,
  favoriteFoods:   [String]
});

var Person = mongoose.model('Person', personSchema);

var joe = new Person({
  name: "Joe",
  age: 24,
  favoriteFoods: ['Apple', 'Banana']
});

joe.save(function(err, persons) {
  if(err){
    console.log("Failed");
  } else {
    console.log("Saved Successful");
    console.log(persons);
  }
});

var createAndSavePerson = function(done) {

  done(null /*, data*/);

};

Answer №1

According to @SQMN's analysis, the FCC task advises creating a new document from the Person model and populating it with data, prior to saving.

var Person = mongoose.model('Person', personSchema);

var p = new Person;
p.name = "John";
p.age = 18;
p.favoriteFoods = ["hotpot", "suantangyu"];
var createAndSavePerson = function(done){
  p.save(function(err, data){
    if (err){
      return done(err);
    }
    return done(null, data);
  });
};

Answer №2

According to a member on the FCC forum named dnlnav, the recommendation is to consolidate your instance and save function into createAndSavePerson and adjust the callback passed into save in this manner:

var createAndSavePerson = function(done) {
  var joe = new Person({
    name: "Joe",
    age: 24,
    favoriteFoods: ['Apple', 'Banana']
  });

  joe.save((err, data) => {
    if (err)
      return done(err);
    return done(null, data);
  });
};
   

Answer №3

The technique you just demonstrated is one I haven't delved into yet. However, I recently discovered that Mongoose has its own method called create(obj,callback) which streamlines most of the process for you. It can be implemented as follows:

const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI);

const Schema = mongoose.Schema;

const personSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  age: Number,
  favoriteFoods: [String]
});

const Person = mongoose.model('Person', personSchema);

Person.create({
  name: "Alice",
  age: 30,
  favoriteFoods: ['Pizza', 'Pasta']
}, function(err, result){
    //Handle errors or successful results here
});

Answer №4

I recently came across a challenge on freeCodeCamp that caught my attention:

  • Creating and Saving Records

If you are currently working on this challenge, make sure to refer to the template myApp.js file where you will find detailed instructions and function declarations for each step. Look out for the empty function named createAndSavePerson() and don't forget to write your logic inside it.

Answer №5

If you're experiencing timeout problems, consider removing the < > tags within the MONGO_URI key or educate yourself on MongoDB fundamentals. You'll uncover the solution.

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

Creating a new row in a Tabulator component in React and retrieving the data

I have incorporated the react-tabulator library into my project and I am looking for guidance on how to dynamically add new rows once the tabulator has been rendered. Ideally, I would like to include a button below the tabulator that enables users to add a ...

Show text upon hovering using jQuery

I am currently exploring jquery and trying to implement a functionality where text is displayed upon hovering over a div element. My basic html page consists of squares, with one of them rotating when a button is clicked. I now want to show some text withi ...

Using PHP's include/require method with a dynamic path

Looking for assistance with my issue! Ajax is returning the correct information and displaying it in an 'alert(html)' on 'success'. The PHP code echoes $idName and $path correctly on the carrier page where the code resides. There are no ...

What is the best way to initialize React-map-gl with the user's current location as the default latitude and longitude?

Is there a way to render the map with default values of viewport set to user's location without needing to click a locate me button? <ReactMapGL mapboxApiAccessToken={mapboxApiKey} mapStyle="mapbox://styles/mapbox/streets-v11" ...

Utilizing a Jquery plugin for enhanced form validation with the inclusion of supplementary techniques

I am looking to integrate a jQuery plugin into my form validation process, specifically to ensure that only letters are allowed in the name section. If a user enters special characters or numbers, I want the form to display an error message. Additionally, ...

Can a function be appropriately utilized in a reducer?

For my reducer, I am looking to incorporate a function that is necessary for sorting. I have successfully imported this function from another file and it seems to be functioning correctly. However, I am unsure about the validity of importing and using fu ...

Is it possible to find a match by searching through multiple arrays for a corresponding variable name?

Hi there, I'm currently working on a function that triggers an alert if the name of an array of images matches the data attribute of the selected element. This is just a test phase before proceeding with my main project, but I've hit a roadblock. ...

Utilizing Chrome Context Script plugin to monitor page changes: A step-by-step guide

Currently, I am in the process of creating a basic Chrome extension with the purpose of removing specific DOM elements from a particular website. In my manifest.json file: { "name": "example", "version": "1.0", "description": "example description" ...

Executing tasks with MongoDB user verification

I recently set up MongoDB for my research project and established two databases: mydb and jobs. After creating a user with the following credentials: db.createUser( { user: "devdbuser", pwd: "123456", roles: [ "readWrite" ] } ) I encountered an interest ...

MongoDB failing to fetch any data

Here is my code snippet: MongoClient.connect(gloabl_vars.db.mongo.url,function(err, db) { if(err) { throw err; } var dbo=db.db("profilemanager"); var mquery={_id:'123454'}; db.collection('userinfo'). ...

Issue with IE11: the selected list is not displayed when using the <s:optiontransferselect> tag

When moving groups from left to right in the s:optiontransferselect for selectedGrps and unselectedGrps, the SelectedGroups list is showing as null on form submission in IE11. However, in Chrome and Mozilla, it functions correctly. Any advice would be grea ...

Identifying an Android device using Javascript or jQuery

Is there a way to identify an Android device for styling a mobile website? I want to add specific CSS styles for users on the Android platform. Appreciate any help! ...

Exploring Chrome's WebUSB Functionality with AngularJS

Recently, I encountered a challenge while utilizing WebUSB APIs for Chrome through AngularJS. This particular project involves accessing an esc/pos thermal printer for the purpose of printing invoices. In typical JavaScript: HTML: <button id="connect ...

Impose a delay between the execution of two functions in React.js

Looking for a way to introduce a forced delay between two consecutive function calls. Essentially, what I want to achieve is: a // call func a delay(100) // pause for 100 ms b // call func b Is there a method to accomplish this? Update: attempted a() ...

To achieve two-way binding with a scope variable, it is necessary to enclose it within an

I am in need of creating a basic search feature for some items. I have designed a simple control with a button that clears the search query: <div class="item item-input item-button-right"> <i class="icon ion-ios-search placeholder-icon">&l ...

Having trouble parsing JSON with Ajax in Pusher using PHP?

I am facing an issue while sending multiple parameters using the Pusher AJAX PHP library. This is the error I encounter: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Here is my PHP and JS code: <script src="https: ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Creating audio streams using react-player

I am currently working on integrating the react-player component from CookPete into my website. However, I am facing a challenge in setting up multiple audio streams. Additionally, I want to include both DASH and HLS video streams but adding them as an arr ...

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

Modify information in the database using Mongoose

Attempting to update data in my database using Mongoose and NodeJS, I am able to retrieve data from the logged in user, but encountering issues with updating it. I have a form on the front-end that fetches data from the logged in user (views/pages/profile- ...