重复的名称功能,如文件系统

时间:2017-04-21 07:49:07

标签: node.js mongodb mongoose

我正在尝试做类似我们计算机的文件系统之类的东西,如果文件名“test”出现在一个文件夹中,我们尝试再创建一个同名文件,那么我们得到结果为“test(01)”如果我们再试一次 然后我们得到结果“test(02)”。

基本上,我想在我的项目中使用这种功能。我正在使用mongoose和nodejs

// schema
var schema = new Schema({
    name: {
        type: String,
        required: true
    }
}, options);

每当用户在数据库中添加名称时,我必须检查是否已存在相同的名称,然后我们在其名称中附加计数。

就像第一次用户添加name = test一样,然后在db中我们将另存为name = test

第二次添加name = test,然后在db中我们将名称保存为name = test(01)

第三次添加name = test,然后在db中我们将名称保存为name = test(02)

等等。

任何人都可以建议帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

你可以添加另一个字段作为版本,当文件出现时检查是否存在任何相同名称的早期文件,如果结果为false / null,则保存为文档,否则将推送为文件版本。

答案 1 :(得分:0)

这是一个粗略的想法。

我会使用正则表达式来查找具有相似名称的所有用户,将它们降序排序,取第一个结果以了解谁是具有最高后缀(digit)的用户 - 以便找出下一个数字。我们的regular expression将为(digit)部分提供一个capturing group可选项。

这将是这样的(不记得这是未经测试的):

// suppose req.body.name = test

let re = new RegExp(`^${req.body.name}(\((.*)\))?$`, 'i'); // e.g. /^test(\((.*)\))?$/i

schema.find({ name: re }).sort('name', -1).limit(1).exec(function (err, users) {
    // there is a user with a similar name already
    if (users.length) {
        // apply regular expression on the matched user's name again to get info
        // about the capturing groups

        // note:
        // > re.exec('test')
        // > [ 'test', undefined, undefined, undefined, index: 0, input: 'test' ]
        // > re.exec('test(02)')
        // > [ 'test(02)', '(02)', '(02)', '(02)', index: 0, input: 'test(02)' ]

        let m = re.exec(users[0].name), digit = 0;
        // take out the number
        if (m && typeof m[1] !== 'undefined') {
            digit = parseInt(m[1].replace(/[^\w]/gi, ''), 10); // e.g. (02) => 2
        }
        let suffix = '(' + (++digit).toString().padStart(2, '0') + ')'; // e.g. 2 => (03)
        req.body.name += suffix;
    }
    schema.create(req.body, function () {
        // etc
    })
})

Small illustration