从shell查看mongo db内容

时间:2014-10-28 04:22:04

标签: node.js mongodb shell rest express

我是node和mongo的新手,并且从mongo shell查看我的数据库内容时遇到了一个奇怪的问题。我构建了一个简单的REST api并具有良好的CRUD功能,但即使数据似乎已保存,我也无法从shell中找到它。

我的节目很简单;我从this example复制了它。

有三个文件:package.json,server.js(主文件)和routes / wines.js。像往常一样安装和配置Mongo数据库(侦听端口27017)。我可以毫无问题地从shell添加,更新,读取和删除集合项。

的package.json:

{
  "name": "wine-cellar",
  "description": "Wine Cellar Application",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "3.x",
    "mongodb": "^1.4.19"
  }
} 

server.js

var express = require('express'),
    wine = require('./routes/wines');

var app = express();

app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());

app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.post('/wines', wine.addWine);
app.put('/wines/:id', wine.updateWine);
app.delete('/wines/:id', wine.deleteWine);

app.listen(3000);
console.log('Listening on port 3000...');

routes / wines.js(非常简单的REST api)

var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('winedb', server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'winedb' database");
        db.collection('wines', {strict:true}, function(err, collection) {
            if (err) {
                console.log("The 'wines' collection doesn't exist. Creating it with sample data...");
                populateDB();
            }
        });
    }
});

exports.findById = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
            res.send(item);
        });
    });
};

exports.findAll = function(req, res) {
    db.collection('wines', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

exports.addWine = function(req, res) {
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.insert(wine, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}

exports.updateWine = function(req, res) {
    var id = req.params.id;
    var wine = req.body;
    console.log('Updating wine: ' + id);
    console.log(JSON.stringify(wine));
    db.collection('wines', function(err, collection) {
        collection.update({'_id':new BSON.ObjectID(id)}, wine, {safe:true}, function(err, result) {
            if (err) {
                console.log('Error updating wine: ' + err);
                res.send({'error':'An error has occurred'});
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(wine);
            }
        });
    });
}

exports.deleteWine = function(req, res) {
    var id = req.params.id;
    console.log('Deleting wine: ' + id);
    db.collection('wines', function(err, collection) {
        collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred - ' + err});
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(req.body);
            }
        });
    });
}

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {

    var wines = [
    {
        name: "CHATEAU DE SAINT COSME",
        year: "2009",
        grapes: "Grenache / Syrah",
        country: "France",
        region: "Southern Rhone",
        description: "The aromas of fruit and spice...",
        picture: "saint_cosme.jpg"
    },
    {
        name: "LAN RIOJA CRIANZA",
        year: "2006",
        grapes: "Tempranillo",
        country: "Spain",
        region: "Rioja",
        description: "A resurgence of interest in boutique vineyards...",
        picture: "lan_rioja.jpg"
    }];

    db.collection('wines', function(err, collection) {
        collection.insert(wines, {safe:true}, function(err, result) {});
    });

};

当我使用curl命令从终端测试api时,我没有问题。我可以从数据库中创建,读取和编辑数据,它在我的终端上显示得很好。

然而,mongo shell是一个不同的故事。当我运行“show dbs”时,我看到列出了我的winedb数据库,但是当我对它运行查询时,它表现得好像数据库是空的:

> use winedb
switched to db winedb
> db.winedb.count()
0
> db.getCollection('winedb')
winedb.winedb
> db.count()
2014-10-28T00:14:26.229-0400 TypeError: Property 'count' of object winedb is not a function
> db.winedb.count()
0
> db.getCollection('winedb').find()
> db.getCollection('winedb').count()
0

同时卷曲一切继续正常。如何在mongo shell上查看我的数据?

2 个答案:

答案 0 :(得分:1)

您可以在here上看到以下查询 并使用robomongo之类的应用程序。这也会给你提问。

获取集合的简单查询

> use winedb
> show collections or tables //this will gives you list of collection
> db.{collectionNAME}.find()
> db.{collectionNAME}.count()
> db.{collectionNAME}.find({id:''})

答案 1 :(得分:1)

您的数据库名为winedb,该集合名为wines,但您一直在尝试在名称空间winedb.winedb而不是winedb.wines中查找文档。在shell中尝试以下内容:

> use winddb
> db.wines.findOne()