2016-01-07 26 views
0

我正在使用Nodejs構建應用程序,我需要在服務器端的集合上執行一些功能。我被告知要使用貓鼬來獲得收藏。這裏是我的代碼到目前爲止:使用貓鼬訪問現有的monogodb集合

 var mongoose = require('mongoose'); 
     var Schema = mongoose.Schema; 
     mongoose.connect('mongodb://localhost/test', function(err){ 
      if(!err){ 
       console.log("no error!") 
      } 
     }); 
     var doc = mongoose.model('foo', 
         new Schema({name : String}), 
         'answers'); 
     doc.find({}, function(err,collection){ 
      console.log(collection) 
     }); 

我想要訪問的集合稱爲'答案'。我想訪問數據並進行一些更改並將其發佈到另一個集合中。上面的代碼打印出一個空數組。我將不勝感激一些幫助。

+1

看起來你已經創建了一個模型,但不添加任何東西到數據庫但,這就是爲什麼你得到一個空回 – adeneo

+1

我沒有用之前的東西添加到數據庫貓鼬。我檢查了它,數據在收集中。 –

+0

代碼看起來不錯。你確定'answers'集合在'test'數據庫中嗎? – JohnnyHK

回答

2

試試這個:

var mongoose = require('mongoose'); 
    var Schema = mongoose.Schema; 
    mongoose.connect('mongodb://localhost/test', function(err){ 
     if(!err){ 
      console.log("no error!") 
     } 
    }); 
    var doc = mongoose.model('answer', new Schema(
     {name : String}) 
    ); 
    doc.find({}, function(err,collection){ 
     console.log(collection) 
    }); 
+0

[Mongoose#model](http://mongoosejs.com/docs/api.html#index_Mongoose-model)api。 – Marco