Mongo schema, array of string with unique values

前端 未结 3 2001
抹茶落季
抹茶落季 2020-12-17 01:39

I\'m creating the schema for a mongo document and I can do everything except prevent duplicates in a non-object array.

I\'m aware of the addToSet, but I\'m referring

相关标签:
3条回答
  • 2020-12-17 01:51

    This method builds on Med's answer, handles references, and done completely in scheme validation.

    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();
    
    });
    
    0 讨论(0)
  • 2020-12-17 01:53

    I've come to the conclusion that this is impossible to do via Mongoose Schema.

    JSON schema is done like so.

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

    I'll validate with JSON schema before creating Mongo Document.

    0 讨论(0)
  • 2020-12-17 02:05
    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);
        })
    });
    
    0 讨论(0)
提交回复
热议问题