2015-07-11 72 views
0

我在寫一個應用程序,它將文檔存儲在MongoDB數據庫中。我想要一個索引號與每個自動生成的文檔相關聯。Mongoose計數函數獲取文件的索引號

我想計算當前在數據庫中的文檔數量並設置索引號。那麼如何使用Mongoose.js計數函數來實現呢?還是有更好的方法來做到這一點?

這是我document.js文件:

var mongoose = require('mongoose'); 

var DocSchema = new mongoose.Schema({ 
    Title: String, 
    Date: Date, 
    Author: String, 
}); 

mongoose.model('Doc', DocSchema); 

回答

1

您將需要也是一個index字段添加到架構這個工作。

var mongoose = require('mongoose'); 
var DocModel = mongoose.model('Doc'); 

var newDoc = new DocModel(); 
newDoc.Title = 'Title of Book'; 
newDoc.Date = new Date(); 
newDoc.Author = 'Author Name';' 

DocModel.count().exec(function(err, count){ 
    newDoc.index = count; 
    newDoc.save(function(err, result){ 
     if(err){ 
      console.log('Error saving new document'); 
      console.log(err); 
      return; 
     } 
     console.log('New document created successfully!); 
    }); 
}); 
+0

請參閱編輯並顯示如何將代碼添加到此! @Matthew Antolovich – OneMoreQuestion

+0

@axc您是否試圖將索引設置爲架構級別? –

+0

完全是在指數層面@Matthew Antolovich – OneMoreQuestion