cnak2
cnak2

Reputation: 1841

Constant not reflected in function

I have a Node/Express/Mongoose API, where I have a function that handles multiple updates to a document based on an ID and Type parameter I pass in to it.

The three params are: type: basically the target field in my document (i.e 'linkedin', 'facebook'...) id: the id of the field of the document I'm trying to update item: the value I'm pushing into the update.

The first thing I do is create a few constants for the query:

  const sharedType = 'shared.' + type + '.item';
  const sharedTypeId = 'shared.' + type + '._id'
  const rootType = type + '.item';
  const rootTypeId = type + '._id'

So for example, I will pass in : rootTypeId:'linkedin' to setup a query parameter for linkedin, which results in a const of 'linkedin._id' which will populate the following:

Cards.update({ rootTypeId: id }, { $set: { rootType: item } }, { 'multi': true }, function (err, card) { err === null ? console.log('No errors ' + type + ' updated for cards') : console.log('Error: ', err); } )

and then I have the other const for rootType, which for linkedin would end up being 'linkedin.name' to target the item field.

My problem is this...

If I hard-code things like so: Cards.update({ 'linkedin._id': id }, { $set: {

it works.

But using the constants doesn't, though they should result as the same parameters.

What am I doing wrong here?

Thanks!!

Upvotes: 0

Views: 46

Answers (1)

Alexander Romanov
Alexander Romanov

Reputation: 433

Try this:

Cards.update({ [rootTypeId]: id }, { $set: { [rootType]: item } }, { 'multi': true }, function (err, card) { err === null ? console.log('No errors ' + type + ' updated for cards') : console.log('Error: ', err); } )

Basically rootTypeId and rootType should be put in square brackets, so values inside these variables become keys in your query object

Upvotes: 1

Related Questions