mongodb:插入数据后数据库不显示在show dbs中

时间:2017-08-10 12:48:28

标签: node.js mongodb mongoose

我正在关注Jose Annunziato的YouTube教程。我创建了server.js并为数据库连接完成了所有必需的设置和配置。现在,当我从表单向服务器发布内容时:它显示数据已成功发送到服务器,但是当我转到mongo控制台以验证是否已收到数据并且是否已创建数据库时。我运行db它说测试我运行show dbs,在那里我看不到我的新数据库。我不确定实际问题是什么,因为我做了Jose在教程中所说的一切。

Server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/blogfall2016');

var PostSchema = mongoose.Schema({
    title: {type: String, required: true},
    body: String,
    tag: {type: String, enum:['POLITICS', 'ECONOMY', 'EDUCATION']},
    posted: {type: Date, default: Date.now},
});

var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/api/blogpost", CreatePost);

function CreatePost(req, res) {
    var post = req.body;
    console.log(post);
    PostModel.create(post);
    res.json(post);

}


app.listen(3000);

2 个答案:

答案 0 :(得分:1)

如果要插入的架构和数据匹配,那么它应该可以正常工作。

尝试以下代码。而不是 PostModel.create(post);

    var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/nnnnnn', function (err) {
    if (!err) {
        console.log('connection successful');
    } else {
        console.log(err)
    }
});

var PostSchema = mongoose.Schema({
    title: { type: String, required: true },
    body: String,
    tag: { type: String, enum: ['POLITICS', 'ECONOMY', 'EDUCATION'] },
    posted: { type: Date, default: Date.now },
});

var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/api/blogpost", CreatePost);

function CreatePost(req, res) {
    var post = req.body;
    console.log(post);
    // static data
    var post = {
        title: 'asdfasdf',
        body: 'asdfasdfasdfasdf',
        tag: 'POLITICS',
        posted: new Date()
    }
    var postModel = new PostModel(post);

    postModel.save(function (err, data) {
        if (err) {
            console.log('Error', err);
        } else {
            console.log('data inserted');
        }
    });


    res.json(post);

}


app.listen(3000);

答案 1 :(得分:0)

而不是下线

mongoose.connect('mongodb://localhost/blogfall2016');

尝试这个以确保首先成功创建数据库, 然后做你的操作

mongoose.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});