【发布时间】:2018-06-15 09:47:13
【问题描述】:
我有 mongod 使用以下命令运行:
$ mongod -f /etc/mongodb.conf
使用此脚本可以正常插入文档:
插入.js
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/edx-course-db';
MongoClient.connect(url, (error, client) => {
if (error) return process.exit(1);
console.log('Connection is OK');
var db = client.db('mytestingdb');
var collection = db.collection('edx-course-students');
collection.insert([
{name : 'Bob'}, {name : 'John'}, {name : 'Peter'}
], (error, result) => {
if (error) {
console.log('error in insert');
return process.exit(1);
}
console.log('result.result.n :' + result.result.n);
console.log('result.ops.length: ' + result.ops.length);
console.log('Inserted 3 documents into the edx-course-students collection');
});
client.close();
})
这是输出:
$ node insert.js
Connection is OK
result.result.n :3
result.ops.length: 3
Inserted 3 documents into the edx-course-students collection
然后我运行find 方法,显示文档(这就是我知道插入工作正常的方式):
find.js
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/edx-course-db';
MongoClient.connect(url, (error, client) => {
if (error) return process.exit(1);
console.log('Connection is OK');
var db = client.db('mytestingdb');
var collection = db.collection('edx-course-students');
collection.find({}).toArray((error, docs) => {
if (error) return process.exit(1);
console.log(`docs.length: ${docs.length}`);
console.log(`Found the following documents:`);
console.dir(docs);
});
client.close();
});
这是输出:
$ node find.js
Connection is OK
docs.length: 3
Found the following documents:
[ { _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Bob' },
{ _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'John' },
{ _id: ObjectID { _bsontype: 'ObjectID', id: [Object] },
name: 'Peter' } ]
问题是我在 MongoDB shell 中看不到文档,我试过这个:
通过以下方式连接到 MongoDB shell:
$ mongo
在 MongoDB shell 中,我可以看到我的数据库 (mytestingdb):
> show dbs
blog 0.031GB
local 0.078GB
mytestingdb 0.031GB
test 0.078GB
并更改为我想要的数据库:
> use mytestingdb
switched to db mytestingdb
我可以看到我的收藏(edx-course-students):
> show collections
edx-course-students
system.indexes
但是find()没有显示文档,count()返回0:
> db.collection.find({});
> db.collection.count();
0
注意:如果我用dropDatabase()删除mytestingdb,像这样:
> db.dropDatabase();
{ "dropped" : "mytestingdb", "ok" : 1 }
find.js 不再显示文档(所以我确定 insert、find 和 shell 命令指向同一个数据库)。
这是我的版本:
$ mongo --version
MongoDB shell version v3.6.1
$ mongod --version
db version v3.0.15
$ node --version
v8.9.1
我在这里缺少什么?我的 shell 命令有问题吗?
如果缺少任何相关信息,请告诉我。
【问题讨论】:
-
你把这些js文件保存在哪里以便能够在mongo中运行它们。