0

I have an Array

var fieldsToFetch = ['name', 'class', 'rollNumber'];

I am using this array into NODE-ORM2 query, in simple words, I am saying to ORM that this are the fields I want to fetch.

Person.find({ surname: "Doe" }).limit(3).offset(2).only("name", "class", "rollNumber").run(function (err, people) {
    // returning only 'name', 'rollNumber' and 'class' properties
    //this is working fine
});

In this code, you can see the .only() function which takes the field names. If I am passing the name here by comma separating then it is working fine but if I do like this

Person.find({ surname: "Doe" }).limit(3).offset(2).only(fieldsToFetch).run(function (err, people) {
    // returning only 'name', 'class' and 'rollNumber' properties
    // not working 

});

I also tried

String(fieldsToFetch ); and fieldsToFetch .toString(); but it converts whole array into a single string. So how can I use this array as a parameter here?

Thankyou.

EDIT

Passing 2 or 3 parameter is not a challenge the main goal is to get all array element as individual elements.

2 Answers 2

1

Because you pass an array, but it want separate strings, so if you use ES6 you can pass like .only(...fieldsToFetch). This is called spread operator. It gets the array, splits it into items and passes them as separate parameters.

Example

function f(a,b,c){
  console.log(a);
  console.log(b);
  console.log(c);
}

var args = [1,2,3];

f(...args);

I pass the array with the spread operator and it splits the array into separate items and assigns to the parameters in direction from left to right.

Sign up to request clarification or add additional context in comments.

8 Comments

but OP needs to put only two elements of array.only("name", "class").
What does ... mean? Is it a kind of operator or you want to say something else?
@ArpitMeena see the link, embedded in answer
@Suren _Srapyan thanks, but it is showing an error SyntaxError: Unexpected token ... and JSHINT is also showing an error: [jshint] 'spread/rest operator' is only available in ES6 (use 'esversion: 6'). (W119)
@ArpitMeena The spread operator needs ES6, but you use older version, you need to pass item by item like .only(fieldsToFetch[0], fieldsToFetch[1])
|
0

Try like this..use array.splice() to remove last element from array.Then use ... spread operator:

var fieldsToFetch = ['name', 'class', 'rollNumber'];

     fieldsToFetch.splice(2,1);//now array  having two elements ['name', 'class']

then

.only(...fieldsToFetch)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.