1
votes

I have a userAccounts Meteor Mongo database where I store the username and posts that the user has liked. This is how it looks:

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

I want each time the user likes another post, to add the post._id to the postId in the likedPosts. So I did something like this:

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

But for some reason it doesn't push the new post id to the array it just keeps the first record that was inserted above, so the insertion works. Any idea what I did wrong? Thanks in advance !

2

2 Answers

0
votes

This is where you use "Dot notation" and you also actually have a $set operation here for the date as well:

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

One "appends to the array" created and the other "sets the new date".

The naming seems a little off to me though, and maybe you meant "updatedAt" there.

0
votes

The problem might be with your selector. When update and remove see a single value as a selector they assume that that value is the _id.

Instead of:

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

Try:

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

Also, when you did your insert with:

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

likedPosts was initialized as an object, not an array of length one. So you can't push onto it. Do instead:

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