简体   繁体   English

如何在Mongo中的所有文档中取消设置唯一字段?

[英]How do I unset a unique field from all documents in Mongo?

I'm using mongoose/nodeJS and I'm writing some migration scripts using node-migrate . 我正在使用mongoose / nodeJS,并且正在使用node-migrate编写一些迁移脚本。

My update script is adding a new computed field to all documents in a collection: 我的更新脚本正在将新的计算字段添加到集合中的所有文档中:

exports.up = function (done) {
  Posts.find({_hash: null}, function (err, posts) {
    async.forEach(posts, function (post, next) {
      var hash = hash(post);
      post.update({_hash: hash}, next);
    }, done);
  });
};

and that works fine. 而且效果很好。 I'm grabbing all docs with no hash field, computing it, and updating the record. 我正在抓取所有没有hash字段的文档,对其进行计算并更新记录。

But node-migrate supports "downward" migrations as well, to rollback changes. 但是node-migrate支持“向下”迁移,以回滚更改。 In this case I want to remove the hash field from all docs that have one. 在这种情况下,我想从所有包含一个的文档中删除哈希字段。

exports.down = function (done) {
  Posts.update({_hash: {$ne: null}}, {$unset: {$hash: 1}}, {multi: true}, done);
};

but i get a duplicate key error. 但我得到重复的密钥错误。 The schema does indeed define that field as uniquely indexed, so that makes sense..? 该架构确实确实将该字段定义为唯一索引的,所以这很有意义。

How can I unset/delete a field from all docs in a collection if that field is defined as unique? 如果该字段定义为唯一字段,如何从集合中的所有文档中取消设置/删除该字段?

Thanks. 谢谢。

A unique index will not allow multiple docs where the indexed field is either missing or null . 唯一索引将不允许索引字段缺失或为null多个文档。

To support this, you will need to drop the existing unique index on hash and re-create it as a unique, sparse index. 为此,您需要将现有的唯一索引放在hash然后将其重新创建为唯一的稀疏索引。

Drop the index in the shell: 将索引放在外壳中:

db.posts.dropIndex('$_hash_1')

Update the definition of hash in your schema to make it a sparse, unique index: 更新架构中hash的定义,使其成为稀疏的唯一索引:

hash: {type: String, index: {unique: true, sparse: true}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM