2013-08-31 31 views
0

我在保存mongodb(Mongoose)中的json對象時遇到問題,所以當我插入一切正常,但是當我提出相同對象的請求時,Mongoose返回一個修改JSON。它像Mongoose自動完成Twitter領域,我不知道爲什麼。在Mongoose中保存/加載json對象之間的區別

這裏是我的代碼:

UserSchema = mongoose.Schema({ 
firstName: String, 
lastName: String, 
email:  String, 
salt:  String, 
hash:  String, 
twitter:{ 
    id:  String, 
    email: String, 
    name:  String 
}, 
facebook:{ 
    id:  String, 
    email: String, 
    name:  String, 
    username: String, 
    photo: String, 
    gender: String 
} 
}); 

我救JSON在我的數據庫:

User.create({ 
     email : profile.emails[0].value, 
     facebook : { 
      id: profile.id, 
      email: profile.emails[0].value, 
      name: profile.displayName, 
      username: profile.username, 
      photo: profile.photos[0].value, 
      gender: profile.gender 
      } 
     }, function(err, user){ 
      if(err) throw err; 
      // if (err) return done(err); 
      done(null, user); 
     }); 

但我當貓鼬返回JSON。

enter image description here

貓鼬在JSON產生的場。推特:{} < ----

我不知道爲什麼,有人可以借我一隻手嗎?

回答

1

如果您查看保存到MongoDB的文檔,您會發現twitter對象實際上並不存在,除非設置了子對象的屬性。創建該對象以便您可以方便地設置屬性,而無需擔心創建子/嵌套對象。所以,你可以這樣做:

var user = new User(); 
user.twitter.id = 'wiredprairie'; 
user.save(); 

結果:

{ "_id" : ObjectId("522259394eb9ed0c30000002"), 
    "twitter" : { "id" : "wiredprairie" }, "__v" : 0 } 

如果你進了一步,並希望該數據的更「純」的看法,你可以在貓鼬模型實例使用toJSON

console.log(user.toJSON()); 

結果:

{ _id: 522259ad3621834411000001, twitter: { id: 'wiredprairie' } } 
+0

我解決了你的答案的問題,我用JSON函數和它的工作很好。謝謝 – slorenzo

相關問題