MongoDB find() 没有返回结果。

7

我正在尝试从mongodb shell查询我的数据库以检索所有条目,但是我的find()方法没有返回任何内容。

这是我使用的mongoose模型:

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

var ArticleSchema = new Schema({
    title: String,
    content: String,
    author: { type: String, default: 'Vlad'},
    postDate: { type: Date, default: Date.now }
});

ArticleSchema.methods.formatTitle = function() {
    var link = this.title.replace(/\s/g, '-');
    return '/article/' + link;
};

ArticleSchema.methods.snapshot = function() {
    var snapshot = this.content.substring(0, 500);
    return snapshot;
};

module.exports = mongoose.model('Article', ArticleSchema);

当在浏览器中加载我的Express.js应用程序时,使用API添加的所有文章都可以正常显示。但是,我只想进入mongo shell并进行查询。我已经使用了以下查询:
// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()

我得到的返回值是空字符串,也就是控制台中的换行符。

您可以在mongodb控制台中始终使用db.getCollectionNames()来查看单个数据库中存在哪些内容。 - WiredPrairie
3个回答

11

你的答案就在问题中:

// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()
所以db已经指向正确的数据库。不要使用blog,而是放置集合名称,而不是数据库名称。
db.articles.find()

我明白了。所以,每当我有一个名为Model的模型时,mongodb会自动生成一个集合(toLowerCase() + 's'),对吗?这就是我之前缺失的部分 :D - vladzam
更有可能的是,mongoose在第一次插入时创建这些集合。顺便说一下,在shell中运行以下命令可以查看所有可用的集合:show collections - Sergio Tulentsev

5

Mongo shell会在启动时连接到test数据库,您需要更改数据库,然后在集合上执行查找:

use blog
db.articles.find()

3
如果数据库名称在URL中包含,那么use语句是不必要的。 - Sergio Tulentsev
如果您更改了第一个数据库的名称,MongoDB仍将在登录URL中显示旧数据库的名称。因此,用户可以切换(或手动在URL中更改)。 - avimimoun

2
首先选择数据库,然后在集合中查找。
use blog
db.articles.find()

在尝试使用find()之前,我已经使用了use blog查询。 - vladzam
你使用过 db.articles.find() 吗?问题中提到了 "db.blog"。 - Andreas Hultgren
这正是我在寻找的,就像Sergio在他的回答中所说的那样 :D 感谢您的快速响应! - vladzam
如果连接字符串中包含数据库名称,则不需要使用use语句。 - Sergio Tulentsev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接