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

Insert data in mongoDB database from node.js

本文关键字:插入 数据 数据库 mongoDB node js      更新时间:2023-09-26

上下文:想要从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)

看来你没有完全掌握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);        
});