Take the id after insert


#1

I’m doing in my collection an insert:
Food.insert(that.plate);

Just after this I’d like to go directly to the plate inserted:
$state.go('food/ID_HERE');

  • How can I take the id after insert without findOne. Is this possible?
  • Can I do a fail or error callback in the insert?

Thanks in advance


#2

The insert returns the _id.

You can check a failed insert by:


let aRecord = Food.insert(that.plate);
if (!aRecord) {
    // handle failure
}

#3

Thanks!

Thanks was exactly what I was looking for.

Thanks for the knowledge about let as well. Never used it before


#4

Glad I could help !

Prefer let and const to var.


#5

I’ve been investigation a bit about var, let and const. I’ve always been using var.
I founds this post about let performance instead var:
https://esdiscuss.org/topic/performance-concern-with-let-const

I’ll keep investigating.

BTW, why you used let instead const.

Sorry for moving to another subject but I find really important.


#6

I prefer using let and const rather than var. As to when to use let vs const, it depends on what happens to your variables within the block structure of your code. For example, taking this code:

var bob = 0;
if (thing) {
  bob = 10;
} else {
  bob = 20;
}
console.log(bob);

the obvious refactor with let is:

let bob = 0;
if (thing) {
  bob = 10;
} else {
  bob = 20;
}
console.log(bob);

Trying this with const would not work, because we are changing the value of bob. Trying to move the const into the if also fails, because let and const are block scoped.

const bob = 0;
if (thing) {
  const bob = 10; // not the same bob as the above bob
} else {
  const bob = 20; // not the same bob as either of the above bobs
}
console.log(bob); // always logs 0

However, you can use const quite flexibly with objects:

const obj = { a:1, b:2 };
obj.c = 3; // allowed - we aren't changing the definition of obj as an object.
obj = 'Bob'; // not allowed

I’ve found that the easiest way to work out what to use is to configure eslint into your editor. It tells you exactly which to use based on the structure of your code :slight_smile: .


#7

Thanks for your comment!

Sometimes, even with years of experience on your back, we forget or ignore important things like this one.

Good info guys