首页 文章

使用$ addToSet和$ each,Mongo和Node JS时出错

提问于
浏览
0

我试图使用$ 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' - ROOFING]

知道为什么会这样吗?

1 回答

  • 0

    终于找到了我的问题 .

    在Schema我有:

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

    哪个正在寻找一个带有String的对象 . 架构应该只是:

    "Classifications": [String]
    

    这允许

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

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

相关问题