BULLETBOT
BULLETBOT

Reputation: 51

How do I do a optional chaining on const? | Node.js

I know it's a dumb question but i can't do it.

This is my code.

taggedUser ?
const reported = new reportModel({
      _id: mdb.Types.ObjectId(),
      User: taggedUser.username,
      UserId: taggedUser.id,
      rByUser: message.author.username,
      rByUserId: message.author.id,
      rReason: args[1]
    });
:
message.channel.send("Didn't find user")

And I can't do it. Can someone help me? I'm new to this.

Upvotes: 0

Views: 79

Answers (2)

Laode Muhammad Al Fatih
Laode Muhammad Al Fatih

Reputation: 4610

The chaining operation is not needed. You can simplify it to be like this:

if (!taggedUser) message.channel.send("Didn't find user")

const reported = new reportModel({
   _id: mdb.Types.ObjectId(),
   User: taggedUser.username,
   UserId: taggedUser.id,
   rByUser: message.author.username,
   rByUserId: message.author.id,
   rReason: args[1]
})

Use chaining operations if you need a return value from the comparison. Use if else if you need to control the flow.

Upvotes: 2

bharat.goli
bharat.goli

Reputation: 159

Statements cannot be used inside expressions.

You can create a reported variable and buildReportModel() function just above taggedUser, to assign new reportModel to reported when taggedUser is true

let reported;

function buildReportModel() {
  reported = new reportModel({
    _id: mdb.Types.ObjectId(),
    User: taggedUser.username,
    UserId: taggedUser.id,
    rByUser: message.author.username,
    rByUserId: message.author.id,
    rReason: args[1]
  });
}

taggedUser ? buildReportModel() : message.channel.send("Didn't find user");

Upvotes: 0

Related Questions