从node.js在mongoDB数据库中插入数据

时间:2014-08-06 05:26:29

标签: javascript node.js mongodb

上下文:想要从node.js

在mongoDB数据库中插入数据

问题陈述:我试图在mongoDB数据库中插入数据但是抛出了错误。无法找到它。

当前输出:参考错误

附加代码:

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>

输出:

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)

1 个答案:

答案 0 :(得分:0)

看来你并没有完全掌握javascript的异步性质。传递给函数的变量仅存在于该函数的范围内。请参阅此评论代码:

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);        
});