【问题标题】:Mongoose returning Object not Array猫鼬返回对象而不是数组
【发布时间】:2018-01-04 13:10:30
【问题描述】:

我一直在努力让我的猫鼬查询返回一个数组,因为我需要:

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

我的代码:

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] [LOG] 对象

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

【问题讨论】:

  • 但是这里console.log(out) 是一个数组,所以问题是什么
  • 其实不是,查看第三条日志显示object,导致报错!谢谢
  • 在javascript中一切都是对象数组也是对象。你可以像这样检查out instanceof Array
  • 嗯不错,但为什么我不能使用 $addToSet 保存它?

标签: node.js mongodb mongoose


【解决方案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  } } })
                });

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 2021-08-20
    相关资源
    最近更新 更多