【问题标题】:Mongo schema, array of string with unique valuesMongodb模式,具有唯一值的字符串数组
【发布时间】:2017-06-06 22:05:17
【问题描述】:

我正在为 mongo 文档创建架构,除了防止非对象数组中的重复之外,我可以做任何事情。

我知道 addToSet,但我指的是 Mongo Schema。

我不想使用 $addToSet 检查更新,而是希望这成为我的架构验证的一部分。

以下示例。

let sampleSchema = {
   name: { type: 'String', unique: true },
   tags: [{ type: 'String', unique: true }]
}

上面的 sn-p 可以防止 name 有重复值。它允许将标签存储为字符串数组。

但是.. 我不能将数组限制为唯一的字符串。

{ name: 'fail scenario', tags: ['bad', 'bad', 'array']}

我可以插入这条记录,这应该是一个失败的场景。

【问题讨论】:

标签: arrays json mongodb mongoose mongoose-schema


【解决方案1】:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const _ = require('underscore');

let sampleSchema = new mongoose.Schema({
  name: {
    type: 'String',
    unique: true
  },
  tags: [{
    type: 'String'
  }]
})
sampleSchema.pre('save', function (next) {
  this.tags = _.uniq(this.tags);
  next();
});
const Sample = mongoose.model('sample', sampleSchema, 'samples');


router.post('/sample', function (req, res, next) {
  const sample = new Sample(req.body);

  sample.save()
    .then((sample) => {
      return res.send(sample);
    })
    .catch(err => {
      return res.status(500).send(err.message);
    })
});

【讨论】:

  • 感谢您的回答,但我正在尝试仅使用 Schema,而不是代码,而不是保存标志,更新猫鼬的方法。
  • 在下划线中,它是 _.uniq 而不是 _.unique。此外,这里是一个修订版,适用于参考:this.tags = _.uniq(this.tags, function(i) {return (i._id) ? i._id.toString() : i;});
【解决方案2】:

我得出的结论是,通过 Mongoose Schema 是不可能做到的。

JSON 模式就是这样完成的。

let schema = {
   name: { type: 'string' }
   tags: { 
      type: 'array',
      items: { type: 'string', uniqueItems: true }
   }
}

我将在创建 Mongo 文档之前使用 JSON 模式进行验证。

【讨论】:

    【解决方案3】:

    此方法建立在 Med 的答案之上,处理引用,并且完全在方案验证中完成。

    let sampleSchema = new mongoose.Schema({
        strings: [{type: 'String'}],
        references: [{type: mongoose.Schema.Types.ObjectId, ref: 'Reference'],
    });
    
    sampleSchema.pre('save', function (next) {
    
        let sample = this;
    
        sample.strings = _.uniq(sample.strings, function(i) {return (i._id) ? i._id.toString() : i;});
        sample.references = _.uniq(sample.references, function(i) {return (i._id) ? i._id.toString() : i;});
    
        return next();
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      相关资源
      最近更新 更多