如何在KeystoneJS中创建唯一键

Chr*_*son 12 mongoose mongodb nosql node.js keystonejs

我正在使用KeystoneJS构建的网站,该网站允许用户发布单词并从其他用户获取建议的同义词.单词是作为短语或句子的一部分提交的,例如"猫是[危险地]接近敲击玻璃."

My Sentence模型如下所示:

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 }
});
Run Code Online (Sandbox Code Playgroud)

我试图根据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 }
});
Run Code Online (Sandbox Code Playgroud)

但是如果我通过提交两个具有相同单词的句子来测试它,它只会使用_id [word] -1,[word] -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);
    }
});
Run Code Online (Sandbox Code Playgroud)

但我想.save只会更新一个现有的独特领域?

Chr*_*son 3

我只能通过使用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();
Run Code Online (Sandbox Code Playgroud)