简体   繁体   English

Mongoose:复制查询结果

[英]Mongoose: copying the result of query

I have a question about copying or mapping the result of query in mongoose.我有一个关于在 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)的结果和(2)的结果应该是一样的,但结果却大不相同。 (1) prints an array of documents filtered by birthYear . (1) 打印由birthYear过滤的文档数组。 However, (2) prints a map whose keys are numbers, which I thought seem to be index of an array.但是,(2) 打印了一个键为数字的映射,我认为它似乎是一个数组的索引。 Can you tell me why this happens?你能告诉我为什么会这样吗?

The result of (1) (1) 的结果

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

The result of (2) (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 . Mongoose 的find()方法在等待时总是返回一个数组,因此您可能应该调用数组users而不是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.在您的代码中,您正在基于提供的数组构建一个新的 JS 对象。 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.所以你混合了扩展运算符的两个用例: ...array复制一个数组,而{ ...obj }obj字段填充新对象。 In this case array is "considered" as object by JavaScript runtime so it's indexes are evaluated as keys.在这种情况下,数组被 JavaScript 运行时“视为”对象,因此它的索引被评估为键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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