如何在KeystoneJS中创build唯一的键
我正在使用KeystoneJS构build的网站,允许用户发布单词并从其他用户那里获取build议的同义词。 单词是作为短语或句子的一部分提交的,例如“猫已经(危险地)接近敲开玻璃杯”。
我的句子模型看起来像这样:
Sentence.add({ sentence: { type: Types.Text, required: true, initial: "New Sentence", index: true }, word: { type: Types.Relationship, ref: 'Word', required: true, index: true, unique: true, initial: true }, submitter: { type: Types.Relationship, ref: 'User', required: true, index: true, unique: true, initial: true }, source: { type: Types.Text }, createdAt: { type: Date, default: Date.now } });
我试图根据Mongoose文档使Word模型独一无二:
var Word = new keystone.List('Word', { map: { name: 'word' }, _id: { from: 'word', path: 'word', unique: true, fixed: false} }); Word.add({ word: { type: Types.Text, required: true, initial: "New word", index: true } });
但是如果我用同一个单词提交两个句子来testing它,那么就用_id [单词] -1,[单词] -2等这个单词作为第二个实例。
我需要能够查询所有使用特定单词的句子,所以我真的需要每个单词一个项目。 但是对于我的生活,我无法弄清楚如何创造一个独特的领域。
当我从负责接受AJAX请求的路由中添加一个新的Word时,可能是我的问题:
var newWord = new Word.model({ word: req.body.word // read from the input box on the home page }); newWord.save(function(err) { if (err) { console.error(err); } });
但我想.save
只会更新现有的独特领域?
你需要像这样改变你的模型的添加方法:
Word.add({ word: { type: Types.Text, required: true, initial: "New word", index: true, unique: true } });
我试了一下,为我工作,通知我增加了独特的:真实的
我使用yeoman的keystone生成器创build了一个keystone项目,并创build了一个类似于你的模型(你可以在model / Test.js中find它),然后在pipe理页面中,当我尝试添加两个相同的单词时,我得到:
Error saving changes to Word 569b98f27b5786db1c367b7a: { [MongoError: E11000 duplicate key error collection: test_unique_field.words index: word_1 dup key: { : "test" }] name: 'MongoError', code: 11000, err: 'E11000 duplicate key error collection: test_unique_field.words index: word_1 dup key: { : "test" }' }
这是链接到回购如果你想玩它: keystonejs_test_unique
我只能通过使用mongoose-unique-validator模块来执行唯一性,如下所示:
var keystone = require('keystone'); var Types = keystone.Field.Types; var uniqueValidator = require('mongoose-unique-validator'); var Word = new keystone.List('Word', { map: { name: 'word' } }); Word.add({ word: { type: Types.Text, index: true, unique: true } }); Word.schema.plugin(uniqueValidator); Word.defaultColumns = 'word'; Word.register();