如何在KeystoneJS

时间:2016-01-07 21:25:31

标签: node.js mongodb mongoose keystonejs nosql

我正在使用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 }
});

我试图根据Mongoose docs使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 }
});

但是,如果我通过提交两个具有相同单词的句子来测试它,那么它只会使用_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);
    }
});

但我认为.save只会更新现有的唯一字段?

2 个答案:

答案 0 :(得分:3)

您需要更改模型的添加方法,如下所示:

Word.add({
    word: { type: Types.Text, required: true, initial: "New word", index: true, unique: true }
});

我试过并为我工作,注意我添加了 unique:true

我使用yeoman的keystone生成器创建了一个keystone项目,并创建了一个像你的模型(你可以在model / Test.js中找到它),然后在管理页面中我尝试添加相同的单词两次我明白了:

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

答案 1 :(得分: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();