简体   繁体   中英

Insert data in mongoDB database from node.js

Context: Want to insert data in mongoDB database from node.js

Problem Statement: I am trying to insert data in the mongoDB database but thrown an error. Cant find it.

Present Output: Reference error

Attach Code:

filter.js

    var server = require('http'),
    express = require('express'),
    http = require('http'),
    fs = require('fs');
    filter = express(),

    io = require('socket.io'),
    mongoose = require('mongoose');

    mongoose.connect('mongodb://localhost/filter_CheckBoxSchema', function(err){
    if(err){
        console.log(err);
    } else{
        console.log('Connected to mongodb!');
    }
});


    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);

    var filter_CheckBoxSchema = mongoose.Schema({
    name: String,
    type: Boolean,
    created: {type: Date, default: Date.now}
    });

    var Filter = mongoose.model('Store', filter_CheckBoxSchema);

    fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    } 

    new Filter({
        name: request.body.name,
        type: request.body.gender,

    }).save(function(err, doc){
        if(err) 
        {
            throw err;
        }
        else
        response.send('Successfully inserted!!!');
    });
});

index.html

<html>
<head>
    <title>Please enter your details</title>
</head>
    <body>
    <h3>Please enter your details</h3>
    <p>Please register below!!!</p>

    <form action="filter.js" method="POST">
    Name: <input type="text" name="Name" />
    <br /><p></p>
    Gender:
    <br /> 
    <input type="radio" name="gender"/> Male
    <br />
    <input type="radio" name="gender"/> Female
    <p></p>
    Interest: (Check all that apply)
    <p>
    </p>
    <input type="checkbox" name="breakfast"/> Breakfast
    <br/>
    <input type="checkbox" name="Lunch"/> Lunch
    <br />
    <input type="checkbox" name="Evening Snacks"/> Evening Snacks
    <br />
    <input type="checkbox" name="Dinner"/> Dinner
    <br />
    <p></p>
    <input type="submit" name="submit" value="Register!!!" />
    </form>
    </body>

</html>

Output:

C:\node\people discovery app>node filter.js
Connected to mongodb!

C:\node\people discovery app\filter.js:152
                name: request.body.name,
                      ^
ReferenceError: request is not defined
    at C:\node\people discovery app\filter.js:152:9
    at fs.js:271:14
    at Object.oncomplete (fs.js:107:15)

It appears you don't completely grasp the asynchronous nature of javascript. Variables passed to a function only exist in that function's scope. See this commented code:

var express = require('express'),
    http = require('http'),
    fs = require('fs'),
    mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/filter_CheckBoxSchema', function(err){
  if(err){
    console.log(err);
  } else{
    console.log('Connected to mongodb!');
  }
});

//Lets read our html file only once, at the very beginning when we first start our nodejs process
fs.readFile('./index.html', function (err, html) {

  //Now in here there are two variables which are accessible, `err` and `html`

  if (err) {
    throw err; 
  } 

  //Create our schema before starting server
  var filter_CheckBoxSchema = mongoose.Schema({
    name: String,
    type: Boolean,
    created: {type: Date, default: Date.now}
  });

  //And now the model as well
  var Filter = mongoose.model('Store', filter_CheckBoxSchema);

  //Now lets start our server
  http.createServer(function(request, response) {
    //The code here is called whenever a new http request is sent to the server
    //There are two variables accessible here, one is `request` which contains
    //data about the original request, while `response` is an object with methods
    //allowing you to respond

    //Here we check what kind of method the browser is using, if its POSTing
    //data then we create a filter from the body
    if (request.method == "POST") {
      new Filter({
        name: request.body.name,
        type: request.body.gender,

      }).save(function(err, doc){
        if(err) 
        {
          throw err;
        }
        else {
          response.send('Successfully inserted!!!');
        }
      });
    }
    else {
      //This must have been a GET request, lets just send `html` instead
      response.writeHeader(200, {"Content-Type": "text/html"});  
      response.write(html);  
      response.end();
    }
  }).listen(8000);        
});

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