2016-01-22 187 views
0

貓鼬不與人口玩得很好。這是我的模型貓鼬填充返回空數組

var mongoose = require('mongoose'), 
Schema = mongoose.Schema; 

mongoose.connect(process.env.MONGO_URI); 

var userSchema = new Schema({ 
    username: String, 
    password: String, 
    books: [{type: Schema.Types.ObjectId, ref: 'User'}] 
    } 
); 

var bookSchema = new Schema({ 
    bookid: {type:String, unique:true, required:true}, 
    imgURL: String 
}); 

module.exports.user = mongoose.model('User', userSchema); 
module.exports.book = mongoose.model('Book', bookSchema); 

數據庫看起來正確。

{ "_id" : ObjectId("56a17cd70a498fcc37cdbe60"), "username" : "test", "password" : "test", "books" : [ ObjectId("56a17d21d43dc32a3a9837de"), ObjectId("56a17ee5d43dc32a3a9837e4"), ObjectId("56a17f5dd43dc32a3a9837e6"), ObjectId("56a17f9fd43dc32a3a9837e8") ], "__v" : 4 } 

但是當我做了我填入得到一個空的「圖書」陣列

users.findOne({'_id':userid}).populate('books').exec(function(err,data){ 
      if (err) return console.error(err); 

      if(data){ 

      } 
}); 

一切都在那裏了,它只是不填充。任何建議將不勝感激。

回答

2

看來refuserSchema中看起來不正確,應該參考book模式而不是user模式本身。

var book = mongoose.model('Book', bookSchema); 

... 
books: [{type: Schema.Types.ObjectId, ref: 'book'}] 
+0

就是這樣。有時它很明顯,謝謝 –