【问题标题】:Error when using $addToSet and $each, Mongo and Node JS使用 $addToSet 和 $each、Mongo 和 Node JS 时出错
【发布时间】:2015-12-10 22:37:04
【问题描述】:

我正在尝试使用 $addToSet 将字符串数组添加到 MongoDB。

对象设置如定义:

var mongoose = require('mongoose'); var Schema = mongoose.Schema;

module.exports = mongoose.model('Company', {
    License: { type: String, index: true },
    "Classifications": [
        {
            Classification: { type: String, _id: false }
        }
    ]
});

当前对象在 Mongo 中是这样的:

{
    "_id": {
        "$oid": "55b03f9337b46f10d38843d7"
    },
    "Classifications": [
        "A - GENERAL ENGINEERING CONTRACTOR",
        "B - GENERAL BUILDING CONTRACTOR",
        "C12 - EARTHWORK AND PAVING"
    ],
    "License": "CA_*****"
}

我正在尝试在以下数组上运行 $addToSet:

var classifications = [ 'B - GENERAL BUILDING CONTRACTOR',
  'C10 - ELECTRICAL',
  'C33 - PAINTING AND DECORATING',
  'C29 - MASONRY',
  'C-9 - DRYWALL',
  'C54 - TILE (CERAMIC AND MOSAIC)',
  'C-5 - FRAMING AND ROUGH CARPENTRY',
  'C20 - WARM-AIR HEATING, VENTILATING AND AIR-CONDITIONING',
  'C36 - PLUMBING',
  'C39 - ROOFING' ]

Company.update({ '_id': company._id }, { $addToSet: { "Classifications": { $each: classifications } } }

当我在 Node 中运行 Company.update 时,出现错误

[TypeError: 不能使用 'in' 运算符在 C39 中搜索 '_id' - 屋顶]

知道为什么会这样吗?

【问题讨论】:

    标签: javascript arrays node.js mongodb mongoose


    【解决方案1】:

    终于解决了我的问题。

    在我拥有的架构中:

    "Classifications": [
            {
                Classification: { type: String, _id: false }
            }
        ]
    

    它正在寻找一个包含字符串的对象。 Schema 应该是:

    "Classifications": [String]
    

    允许

    Company.update({ '_id': company._id }, { $addToSet: { "Classifications": { $each: classifications } } }
    

    运行和添加数组中的字符串没有问题

    【讨论】:

      猜你喜欢
      • 2014-08-09
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 2015-11-07
      • 1970-01-01
      相关资源
      最近更新 更多