B
B
bpGusar2019-10-07 14:57:54
JavaScript
bpGusar, 2019-10-07 14:57:54

Why, after assignment, an array of objects becomes a string array in which objects are represented as strings?

there is such a function on the server:

function findBooks(res, data = {}, fullBookInfo = null) {
  Book.find(data, (err, books) => {
    if (err) {
      res.json(config.getRespData(true, MSG.internalErr500, err));
    } else if (fullBookInfo === "true") {
      const book = _.clone(books[0]);

      Authors.find(
        { _id: { $in: book.bookInfo.authors } },
        (authorsErr, authors) => {
          if (authorsErr) {
            book.bookInfo.authors = null;
          } else {
            book.bookInfo.authors = [...authors];
          }
        }
      );
      res.json(config.getRespData(false, null, book));
    } else {
      res.json(config.getRespData(false, null, books));
    }
  });
}

here
book.bookInfo.authors = [...authors];
, in theory, an array of objects should be assigned, since authors is an array of objects, but after assignment it becomes a string array in which objects are represented as strings.
["{ createdAt: 2019-10-07T11:43:18.207Z,\n  _id: 
5d666abbe480bd41207b1398,\n  authorName: 'Джордж Мартин',\n  __v: 0 }"]

what could be the problem? I don't understand at all

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vadimMalovaniy, 2019-10-07
@vadimMalovaniy

Are you querying MongoDB? This is all because the database gives you JSON.

0
0ffff0, 2019-10-07
@0ffff0

Because json needs to be parsed, i.e. decode json string

E
Evgeny Simonenko, 2019-10-09
@easimonenko

If the query used Promise, then to get an array of records, you would need to add .toArray() to find().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question