2017-06-17 11 views
1

私はユーザー名とユーザーが好きな投稿を格納するuserAccounts Meteor Mongoデータベースを持っています。これは、それがどのように見えるかです:MongoDBプッシュレコードの配列

userAccounts.insert({ 
    username:Meteor.user().username, 
    likedPosts:{ 
     postId:[this._id], 
     createdAt:new Date() 
    } 
    }); 

私は、ユーザーがlikedPostsにpostIdにpost._idを追加するために、別のポストが好きなたびをしたいです。

userAccounts.update(
    Meteor.user().username,{ 
     $push:{ 
     'likedPosts':{ 
      'postId':this._id, 
      'createdAt':new Date() 
     }} 
}); 

しかし、それはそれだけで上記挿入された最初のレコードを保持し、その挿入が機能する配列に新しいポストIDをプッシュしていない何らかの理由:だから私はこのような何かをしました。私が間違っていたことは何ですか?前もって感謝します !

答えて

0

これは、あなたも実際にここにも$set操作日付の持っている:代わりに行います

userAccounts.update(
    Meteor.user().username, 
    { 
    '$push':{ 'likedPosts.postId': this._id } 
    '$set': { 'likedPosts.createdAt':new Date() } 
    } 
); 

つ作成され、「その他「のアレイに追加」新しい日付を設定します。

名前はちょっとわかりませんが、おそらくあなたは"updatedAt"を意味していました。

0

セレクタに問題がある可能性があります。 updateremoveがセレクタとして単一の値を参照するとき、その値は_idと仮定します。

の代わりに:

userAccounts.update({ 
    Meteor.user().username,{ 
     $push:{ 
     'likedPosts':{ 
      'postId':this._id, 
      'createdAt':new Date() 
     }} 
}); 

試してください:あなたとあなたの挿入をしたとき

userAccounts.update({ username: Meteor.user().username }, 
    { $push: { 
    'likedPosts': { 
     'postId':this._id, 
     'createdAt':new Date() 
    } 
    }} 
); 

はまた、:

userAccounts.insert({ 
    username:Meteor.user().username, 
    likedPosts:{ 
     postId:[this._id], 
     createdAt:new Date() 
    } 
    }); 

likedPostsオブジェクト、ないと初期化されました長さ1の配列だからあなたはそれを押すことはできません。あなたが"Dot notation"を使用する場所

userAccounts.insert({ 
    username:Meteor.user().username, 
    likedPosts: [{ 
     postId: [this._id], 
     createdAt: new Date() 
    }] 
    }); 
+0

違いはありません。 – Roberto