MongoDB find()什么都不返回

vla*_*zam 4 mongoose mongodb node.js express

我试图从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);
Run Code Online (Sandbox Code Playgroud)

在浏览器中加载我的Express.js应用程序时,我没有显示使用我的API添加的所有文章的问题.不过,我只想进入mongo shell并查询它们.我使用了以下查询:

// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*sev 7

你的答案就在那里,问题是:

// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()
Run Code Online (Sandbox Code Playgroud)

所以db 已经指的是正确的数据库.而不是blog,放入集合名称,而不是数据库名称.

db.articles.find()
Run Code Online (Sandbox Code Playgroud)


ric*_*dtz 5

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

use blog
db.articles.find()
Run Code Online (Sandbox Code Playgroud)

  • 如果 url 中包含数据库名称,则不需要 `use` 语句 (3认同)