Mongo模式,具有唯一值的字符串数组 [英] Mongo schema, array of string with unique values
问题描述
我正在为mongo文档创建架构,除了防止在非对象数组中重复之外,我可以做所有事情.
I'm creating the schema for a mongo document and I can do everything except prevent duplicates in a non-object array.
我知道addToSet,但是我指的是Mongo Schema.
I'm aware of the addToSet, but I'm referring to Mongo Schema.
我不想使用$ addToSet来检查Update,而是希望它成为我的模式验证的一部分.
I don't want to check on Update using $addToSet, rather I want this to be part of my schema validation.
下面的例子.
let sampleSchema = {
name: { type: 'String', unique: true },
tags: [{ type: 'String', unique: true }]
}
以上代码段可防止名称重复值.它允许将标签存储为字符串数组.
The above snippet prevents name from having duplicate values. It allows tags to be stored as a string array.
但是..我不能将数组限制为唯一的字符串.
But.. I cannot limit the array to be unique strings.
{ name: 'fail scenario', tags: ['bad', 'bad', 'array']}
我可以插入此记录,这应该是失败的情况.
I'm able to insert this record which should be a fail scenario.
推荐答案
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 = _.unique(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);
})
});
这篇关于Mongo模式,具有唯一值的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!