5

我正在尝试从 mongodb shell 查询我的数据库以检索所有条目。不过,我的 find() 方法什么也没返回。

这是我正在使用的猫鼬模型:

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()

我得到一个空字符串作为回报,基本上是控制台中的一个新行。

4

3 回答 3

8

您的答案就在那里,在问题中:

// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()

所以db 已经引用了正确的数据库。而不是blog,放置集合名称,而不是数据库名称。

db.articles.find()
于 2013-09-20T09:45:53.727 回答
4

Mongo shell 将在启动时连接到测试数据库,您需要更改数据库,然后在您的集合上执行 find :

use blog
db.articles.find()
于 2013-09-20T09:50:12.253 回答
1

首先选择 db,然后在 collection 上找到。

use blog
db.articles.find()
于 2013-09-20T09:45:31.787 回答