简体   繁体   中英

Mongoose: copying the result of query

I have a question about copying or mapping the result of query in mongoose. The following is my code.

const user = await User.find({ birthYear: 1990 }).populate("friends").exec();
console.log(user); // (1)
console.log({ ...user }); // (2)

I thought the result of (1) and the result of (2) should be same, but the results are very different. (1) prints an array of documents filtered by birthYear . However, (2) prints a map whose keys are numbers, which I thought seem to be index of an array. Can you tell me why this happens?

The result of (1)

[
  {
    _id: ...,
    birthYear: 1990,
    lotsOfData: ...,
  },
  {
    _id: ...,
    birthYear: 1990,
    lotsOfData: ...,
  }
]

The result of (2)

{
  '0': {
    _id: ...,
    birthYear: 1990,
    lotsOfData: ...,
  },
  '1': {
    _id: ...,
    birthYear: 1990,
    lotsOfData: ...,
  }
}

Mongoose's find() method always returns an array when awaited so probably you should call your array users instead of user . To copy your array you should use

console.log( ...user );

In your code you're building a new JS object based on provided array. Therefore spread operator takes array indexes as keys and puts your array's objects as values into your new object (because you used curly braces).

So you mixed two use-cases for spread operator: ...array copies an array while { ...obj } populates new object with obj fields. In this case array is "considered" as object by JavaScript runtime so it's indexes are evaluated as keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM