2016-08-26 22 views
0

私はmongoをローカルで実行しています。ここで私は私のデータベースにエントリを挿入し、それがここでmongodbから値を取得することができません。

MongoDB shell version: 3.2.9 
connecting to: test 
> use testing 
switched to db testing 
> db.vetschool.insert({name: 'My First Cat'}) 
WriteResult({ "nInserted" : 1 }) 
> db.vetschool.findOne() 
{ "_id" : ObjectId("57c051cbd7bd69709fa7d98a"), "name" : "My First Cat" } 

私は私のスキーマを定義する存在確認し、null値を返しfindOne()関数を実行します。表示されていませんが、私は文書の先頭にmongooseが必要です。

mongoose.connect('mongodb://localhost/test'); 
var db = mongoose.connection; 
db.on('error', console.error.bind(console, 'connection error:')); 
db.once('open', function() { 
    console.log('Successfully connected to MongoDB'); 
}); 
var kittySchema = mongoose.Schema({ 
    name: String 
}); 

var Kitten = mongoose.model('Kitten', kittySchema); 

Kitten.findOne().exec(function(err, success){ 
     console.log(success); //returns null 
     console.log(err); //returns null 
}) 

これはおそらく、あまりにも多くの付加的な情報であるが、ここで私は、サーバーと出力

[nodemon] starting `node server.js` 
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html 
Listening on port 3000... 
Successfully connected to MongoDB 
null 
null 

答えて

1

短い答えはnull値を起動したときに出力されます:あなたは、ドキュメントを挿入するためにモンゴを使用しています手でvetschoolコレクションに入り、MongooseにKittensコレクション内のその文書を探すように依頼します。

長い答え:あなたが渡したスキーマ名に基づいてMongooseがコレクションの名前を自動的に決定します。 http://mongoosejs.com/docs/models.htmlから:手動マングースといくつかのものを経由していくつかのことを行う場合

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.

だから、それはコレクション名が一致することを確認するのはあなた次第です。

+0

お返事ありがとうございます!私は他の何かを欠いているかもしれないように見えます。私はKittensコレクションを作成し、エントリを追加し、mongoとサーバーを再起動し、まだnullを取得しました。 –

+0

私はそれを理解して、あなたの答えは間違いなく助けになりました。コレクションがどのように決定されたかを述べた後、どのデータベースを調べるか指定していないことを認識し、実際にコレクションを作成する前に別のデータベースを作成していました。子猫というタイトルのデフォルトデータベースにコレクションを作成しました。 好奇心のために、私は別のデータベースをどのように指定しますか? –

+0

オハイオ州、はい、データベース名も異なります( 'test'対' testing')! http://mongoosejs.com/docs/connections.html#multiple_connectionsによると、接続文字列にデータベース名を指定することができます。したがって、 'mongodb:// localhost/test'の代わりに、データベース' foo'に対して 'mongodb:// localhost/foo'を使用してください。 –

関連する問題