Ionic2 + Meteor: get _id of new inserted item

2019-09-16 11:59发布

问题:

I'm in an Ionic2 project with a Meteor Database. When I insert a new Item to the database I would need to get the newly generated _id. But I don't know how to access the Observable in the right way.

Server:

newItem() {
   if (!this.userId)
     throw new Meteor.Error('unauthorized', 'User must be logged-in to insert an item');

   return Items.insert({ ownerId: this.userId, title: 'New Item' });
}

Client:

MeteorObservable.call('newItem').subscribe({

  next: () => {
    //get _id 
  },

  error: (e: Error) => {
    console.log("Error: " + e);
  }

});

Items.insert returns an Observable<string> containing the inserted _id. How can I access this _id within next: () on client side?

Edit: I also tried this on the client:

MeteorObservable.call('newItem').subscribe(
  data => {
    console.log(data);
  },
  error => {
    console.log("Error: " + error);
  }
);

But there data is an empty Object Object {_isScalar: false}. :(

Edit2: I also posted it here: https://forums.meteor.com/t/get--id-after-insert-from-returned-observable-on-client/32106

回答1:

The error was on the server-side:

Items.collection.insert(...)

With the added .collection it's returning the new _id-string.