Mongoose返回Object不是Array

时间:2018-01-04 13:10:30

标签: node.js mongodb mongoose

我努力让我的mongoose查询返回一个数组,因为我需要:

  1. 从一个集合中查找0..N文档;
  2. 将此找到的数组保存在另一个嵌套的doc集合中;
  3. 我的代码:

    CarIndex.find({ '_id': { $in: ids } }, 'carID carBrand carModel location')
                .then(collections => {
                    const out = []
    
                    collections.map( (doc) => {
                        const {carID ,carBrand ,carModel ,location} = doc
                        const car = {carID ,carBrand ,carModel ,location};
                        out.push(car)
                    })
    
                    console.log(out)
                    console.log(out.length)
                    console.log(typeof out)
    
                    return CarCollection.findOneAndUpdate({ '_id': collectionId }, { $addToSet: { carCollection: { $each: { out } } } })
                });
    

    输出错误:

      

    [04/01/2018 11:04:48.980] [日志]

    [ { carID: 'd82e41b0-f14f-11e7-b845-990cb852c2b3',
        carBrand: 'Peugeot',
        carModel: '207 Sed. Passion XR Sport 1.4 Flex 8V 4p',
        location: [-23.539727799999998,-46.5111749] },
      { carID: 'd82f2c10-f14f-11e7-b845-990cb852c2b3',
        carBrand: 'Nissan',
        carModel: 'Sentra 2.0/ 2.0 Flex Fuel 16V Mec.',
        location: [-23.607240972099525,-46.72912079051677] } ]
    
      

    [04/01/2018 11:04:48.982] [日志] 2

         

    [04/01/2018 11:04:48.983] [日志]对象

         

    [04/01/2018 11:04:48.997] [错误] MongoError:$ each的参数   $ addToSet必须是一个数组,但它的类型为object

1 个答案:

答案 0 :(得分:1)

你可以这样做

 CarIndex.find({ '_id': { $in: ids } }, 'carID carBrand carModel location')
                .then(collections => {
                    const out = []

                    collections.map( (doc) => {
                        const {carID ,carBrand ,carModel ,location} = doc
                        const car = {carID ,carBrand ,carModel ,location};
                        out.push(car)
                    })

                    console.log(out)
                    console.log(out.length)
                    console.log(typeof out)

                    return CarCollection.findOneAndUpdate({ '_id': collectionId }, { $addToSet: { carCollection: { $each: out  } } })
                });