简体   繁体   English

Mongo无法创建数据库

[英]Mongo can't create the database

I have some problems working with mongo(mongoose on nodeJS), i think these are newbie questions, but i am new to this stuff and i am learning the beginning steps, basically i created a schema on nodeJS and connected the app to mongoDB. 我在使用mongo(nodeJS上的mongoose)时遇到一些问题,我认为这是新手问题,但是我对这些东西不熟悉,我正在学习开始的步骤,基本上我在nodeJS上创建了一个架构并将应用程序连接到mongoDB。 Below is my code for that: 下面是我的代码:

var config = require('./config');
var mongoose = require('mongoose');
var connectionString = "mongodb://localhost:27017/ShareIdea"

module.exports = function(){
    mongoose.Promise = global.Promise;
    var db = mongoose.connect(connectionString);

    require('../app/models/user.server.model');

    return db;
};

then on the server side, i instantiate the mongoose, but my main problem is with the form, i want to post the data. 然后在服务器端,我实例化了猫鼬,但是我的主要问题是表单,我想发布数据。 my form is this: 我的形式是这样的:

<form class="form" action="/users" method="POST">
            <div class="some-class">
                <input type="radio" class="radio" name="userChoice" value="programmer" id="y" />
                <label for="y">Programmer</label>
                <input type="radio" class="radio" name="userChoice" value="inovator" id="z" />
                <label for="z">Inovator</label>
            </div>
            <input class="inp" type="text" name="firstname" placeholder="First Name">
            <input class="inp" type="text" name="lastname" placeholder="Last Name">
            <input class="inp" type="text" name="userame" placeholder="Username">
            <input class="inp" type="email" name="email" placeholder="Email">
            <input class="inp" type="password" name="password" placeholder="Password">
            <input type="submit" class="submit inp" value="Submit">
        </form>

this calls my router that works well, in my schema i set the names to be the same as here: 这调用了运行良好的路由器,在我的模式中,我将名称设置为与此处相同:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    firstname:String,
    lastname:String,
    email:String,
    username:String,
    password:String,
    userChoice: {type: String, possibleValues: ['programmer','Inovator']}
});

mongoose.model('User',UserSchema);

So my database is not creating on its own as i read in other websites, so i typed 所以我的数据库不是像我在其他网站上看到的那样独自创建的,所以我键入

'use shareIdeas' “使用shareIdeas”

in the cmd to create the database, writing 在cmd中创建数据库,编写

show dbs 显示数据库

does not show my create database, when i save the form data i don't know if i am actually saving the data, since i don't have the database, i have no idea if it is saving in a different place. 不显示我的创建数据库,当我保存表单数据时,我不知道我是否实际上在保存数据,因为我没有数据库,所以我不知道它是否保存在其他位置。

here is how i save the form data: 这是我保存表单数据的方式:

var User = require('mongoose').model('User');

module.exports = {

  create: function(req,res){
  var user = new User(req.body);

  user.save(function (err) {
      if (err) {
          return next(err);
      }
      res.json(user);
  });


 },

};

So here change the user to User.And pass the user which contains the data to save. 因此在这里将用户更改为User。并传递包含要保存的数据的用户。

var User = require('mongoose').model('User'); var User = require('mongoose')。model('User');

module.exports = {

  create: function(req,res){
  var user = new User(req.body);

  User.save(user, function (err) {
      if (err) {
          return next(err);
      }
      res.json(user);
  });


 },

}; };

Here is the working code. 这是工作代码。

Call the open (connectToMongoDatabase) and close (closeMongoConnection) connection functions defined in the module in post method. post方法中调用模块中定义的open(connectToMongoDatabase)和close(closeMongoConnection)连接函数。

var express = require('express');
var mongoose = require('mongoose');
var connectionString = "mongodb://localhost:27017/ShareIdea"

module.exports = {

    connectToMongoDatabase: function () {
        mongoose.Promise = global.Promise;
        mongoose.connect(connectionString);
        console.log("MongoDB connected ...");        
    },

    closeMongoConnection : function () {
        mongoose.connection.close();
    }
};

var app = express();

var bodyParser = require('body-parser');
var app = express();
var urlencoded_body_parser = bodyParser.urlencoded({
    extended: true
});

app.use(urlencoded_body_parser);

var Schema = mongoose.Schema;

var UserSchema = new Schema({
    firstname: String,
    lastname: String,
    email: String,
    username: String,
    password: String,
    userChoice: { type: String, possibleValues: ['programmer', 'Inovator'] }
});

var UserModel = mongoose.model('User', UserSchema);

var exports = module.exports;

app.post("/users", function (req, res) {

    console.log(exports);
    exports.connectToMongoDatabase();
    console.log(req.body);
    var user = new UserModel(req.body);

    user.save(function (err, success) {
        console.log(err);
        if (err) {
            console.log(err);
            res.send(err);
        }
        else {
            console.log("inserted.......");
            console.log(success);
            res.json(success);
        }
        exports.closeMongoConnection();
    });

});

app.listen(3000);

The above code has been tested successfully. 上面的代码已成功测试。

用户集合

用户收集数据

You created the database with the name ShareIdea but you are giving use shareIdeas how can this query shows the data in database that you have created.You should use like this use ShareIdea .You want to see that your database is created or not using show dbs this query shows the databases that had the data within it.I created the database in config.js file: 您创建了名为ShareIdea的数据库,但是您要赋予use shareIdeas这个查询如何显示所创建的数据库中的数据。您应该像use ShareIdea那样use ShareIdea 。要查看是否已创建数据库,或者不使用show dbs该查询显示其中包含数据的数据库。我在config.js文件中创建了该数据库:

module.exports = {
'mongoUrl' : 'mongodb://localhost:27017/live_stream'
}

and in my app.js file I gave connection to database and server file 在我的app.js文件中,我连接到数据库和服务器文件

var config = require('./config');
var mongoose = require('mongoose');
var db = mongoose.connection;
mongoose.connect(config.mongoUrl);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});

after creating the schema you should import into the server file ie, app.js 创建模式后,您应该导入服务器文件即app.js

var User= require('./models/User');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM