【问题标题】:Mongodb using addtoSet to ensure there are no duplicatesMongodb 使用 addtoSet 确保没有重复
【发布时间】:2015-02-10 09:37:34
【问题描述】:

对 mongodb 2.6 使用 mongoose - 另一个问题与我的类似;

https://github.com/LearnBoost/mongoose/issues/1677

我有这段代码:

$addToSet: { 
  invite_list: { 
    $each : [ 
      { email: 'test@test.com' }, 
      { email: 'test@test.com' }, 
      { email: 'test@test.com' },
      { email: 'test@test.com' }] 
  }
}

它应该只存储一个项目,而不是存储 4 个!

但是,将查询更改为此

$addToSet: {
  invite_list: { 
    $each : [
      'test@test.com', 
      'test@test.com', 
      'test@test.com', 
      'test@test.com' ]
  }
}

按预期返回一项。

模型架构字段:

invite_list: [{email: {type: String, trim: true}}],

查询如下所示;

UserModel.findOneAndUpdate(
        {
            _id: req.params.id,
        },
        {
            $addToSet: {invite_list: { $each : [{ email: 'test@test.com' },
                { email: 'test@test.com' },
                { email: 'test@test.com' },
                { email: 'test@test.com' }] }}
        }, function (err, user) {
            // morel logic here...        
            return res.status(200).json(user);
        });

http://docs.mongodb.org/manual/reference/operator/update/addToSet/

我有什么遗漏吗?

谢谢。

J

【问题讨论】:

  • 我测试了两个更新查询。他们俩都只添加了一项。
  • 这是确切的代码,还是显示问题的示例?如果您的对象比问题中的示例更复杂,请从文档中记住这一点。 如果数组中的现有文档与要添加的文档完全匹配,则MongoDB确定该文档是重复的;即现有文档具有完全相同的字段和值,并且字段的顺序相同。
  • 只有架构像这样的invite_list: [{type: String, trim: true}],它才能按预期工作。我错过了什么吗?

标签: node.js mongodb testing mongoose database


【解决方案1】:

读完后,我开始思考;

Stop Mongoose from creating _id property for sub-document array items

找到了解决办法;

模型现在看起来像这样;

 var subSchema = new mongoose.Schema({email: {type: String, trim: true, _id: false}},{ _id : false })

invite_list: [subSchema], 

按预期工作...

J

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 1970-01-01
    • 2013-10-23
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2018-04-18
    • 1970-01-01
    相关资源
    最近更新 更多