mongoose-slug-updater
Advanced tools
Comparing version
@@ -1,8 +0,8 @@ | ||
'use strict'; | ||
const _ = require('deepdash')(require('lodash')); | ||
const fs = require('fs'); | ||
var getSlug = require('speakingurl'), | ||
shortId = require('shortid'); | ||
const getSlug = require('speakingurl'); | ||
const shortId = require('shortid'); | ||
module.exports = function plugin(schema, options) { | ||
@@ -16,10 +16,10 @@ options = _.merge( | ||
}, | ||
options | ||
options, | ||
); | ||
var slugs = []; | ||
const slugs = []; | ||
function schemaTraversal(schema, basePath, cb) { | ||
if (basePath) basePath += '.'; | ||
schema.eachPath(function(schemaPath, schemaType) { | ||
schema.eachPath((schemaPath, schemaType) => { | ||
if (schemaType.caster && schemaType.caster.schema) { | ||
@@ -31,3 +31,3 @@ schemaTraversal( | ||
(schemaType.constructor.schemaName == 'DocumentArray' ? '.$' : ''), | ||
cb | ||
cb, | ||
); | ||
@@ -41,8 +41,8 @@ } else { | ||
if (!options.backwardCompatible) return opts; | ||
let res = _.cloneDeep(opts); | ||
let deprecated = ['unique_slug', 'slug_padding_size']; | ||
let found = []; | ||
_.each(deprecated, oldo => { | ||
const res = _.cloneDeep(opts); | ||
const deprecated = ['unique_slug', 'slug_padding_size']; | ||
const found = []; | ||
_.each(deprecated, (oldo) => { | ||
if (res[oldo] !== undefined) { | ||
let newo = _.camelCase(oldo); | ||
const newo = _.camelCase(oldo); | ||
found.push([oldo, newo]); | ||
@@ -56,3 +56,3 @@ res[newo] = res[oldo]; | ||
'Deprecated "snake_case" options found by slug updater plugin. Please update to camelCase.', | ||
found | ||
found, | ||
); | ||
@@ -64,3 +64,3 @@ } | ||
console.log( | ||
'Deprecated option "uniqueGroup" found by slug updater. Please update to uniqueGroupSlug.' | ||
'Deprecated option "uniqueGroup" found by slug updater. Please update to uniqueGroupSlug.', | ||
); | ||
@@ -72,3 +72,3 @@ } | ||
console.log( | ||
'Deprecated option "force_id" found by slug updater. Please update to forceIdSlug.' | ||
'Deprecated option "force_id" found by slug updater. Please update to forceIdSlug.', | ||
); | ||
@@ -79,5 +79,3 @@ } | ||
delete res.on; | ||
console.log( | ||
'Deprecated option "on" found by slug updater. Please update to slugOn.' | ||
); | ||
console.log('Deprecated option "on" found by slug updater. Please update to slugOn.'); | ||
} | ||
@@ -87,11 +85,7 @@ return res; | ||
schemaTraversal(schema, '', (schemaPath, schemaType) => { | ||
if ( | ||
schemaType.instance == 'String' && | ||
schemaType.options && | ||
schemaType.options.slug | ||
) { | ||
let opts = renameOldOptions(schemaType.options); | ||
if (schemaType.instance == 'String' && schemaType.options && schemaType.options.slug) { | ||
const opts = renameOldOptions(schemaType.options); | ||
let basePath = schemaPath.replace(/[\.][^\.]+$/, ''); | ||
if (basePath == schemaPath) basePath = ''; | ||
var slug = { | ||
const slug = { | ||
path: schemaPath, | ||
@@ -114,3 +108,5 @@ basePath, | ||
} else { | ||
console.warn(`slug option expected to be string or array. ${typeof opts.slug} found and will be ignored.`); | ||
console.warn( | ||
`slug option expected to be string or array. ${typeof opts.slug} found and will be ignored.`, | ||
); | ||
return; | ||
@@ -160,2 +156,3 @@ } | ||
schema.pre('findOneAndUpdate', async function() { | ||
// console.log('pre findOneAndUpdate'); | ||
return onUpdate.bind(this)('findOneAndUpdate'); | ||
@@ -167,4 +164,4 @@ }); | ||
// console.log(` = ${operation} ${me.model.modelName} = \n`); | ||
let upd = me.getUpdate(); | ||
let doc = _.cloneDeep(upd); | ||
const upd = me.getUpdate(); | ||
const doc = _.cloneDeep(upd); | ||
if (doc.$set) { | ||
@@ -176,5 +173,5 @@ _.forOwn(doc.$set, (v, k) => { | ||
} | ||
let docs = [_.cloneDeep(doc)]; | ||
const docs = [_.cloneDeep(doc)]; | ||
let unwoundSlugs = unwindSlugs(doc, _.filter(slugs, `on.${operation}`)); | ||
const unwoundSlugs = unwindSlugs(doc, _.filter(slugs, `on.${operation}`)); | ||
if (!unwoundSlugs.length) { | ||
@@ -184,32 +181,24 @@ return; | ||
let updFields = _.keysDeep(doc); | ||
const updFields = _.keysDeep(doc); | ||
// let updPaths = _.map(updFields, f => | ||
// _.trim(f.replace(/\["?(.+?)"?\]/g, '.$1'), '.') | ||
// ); | ||
let involvedPaths = _.uniq( | ||
unwoundSlugs.reduce( | ||
(acc, slug) => acc.concat(slug.fields).concat([slug.path]), | ||
[] | ||
) | ||
).map(p => p.replace(/^\//, '')); | ||
let involvedValuesDocs = await me.model[ | ||
operation == 'updateOne' ? 'findOne' : 'find' | ||
]( | ||
const involvedPaths = _.uniq( | ||
unwoundSlugs.reduce((acc, slug) => acc.concat(slug.fields).concat([slug.path]), []), | ||
).map((p) => p.replace(/^\//, '')); | ||
let involvedValuesDocs = await me.model[operation == 'updateOne' ? 'findOne' : 'find']( | ||
me.getQuery(), | ||
_(involvedPaths) | ||
.map(k => [k.replace(/\.[$\d]+\./g, '.'), 1]) | ||
.map((k) => [k.replace(/\.[$\d]+\./g, '.'), 1]) | ||
.fromPairs() | ||
.value() | ||
.value(), | ||
); | ||
if (involvedValuesDocs) { | ||
if (!_.isArray(involvedValuesDocs)) | ||
involvedValuesDocs = [involvedValuesDocs]; | ||
if (!_.isArray(involvedValuesDocs)) involvedValuesDocs = [involvedValuesDocs]; | ||
involvedValuesDocs.forEach((freshDoc, i) => { | ||
if (i) docs[i] = _.cloneDeep(doc); | ||
involvedPaths.forEach(function(f) { | ||
let fs = unwindPath(freshDoc, f); | ||
_.each(fs, f => { | ||
if (_.get(docs[i], f) === undefined) | ||
_.set(docs[i], f, _.get(freshDoc, f)); | ||
involvedPaths.forEach((f) => { | ||
const fs = unwindPath(freshDoc, f); | ||
_.each(fs, (f) => { | ||
if (_.get(docs[i], f) === undefined) _.set(docs[i], f, _.get(freshDoc, f)); | ||
}); | ||
@@ -220,5 +209,6 @@ }); | ||
} | ||
// console.log('docs', docs); | ||
let slugsUpd = []; | ||
let cache = {}; | ||
const slugsUpd = []; | ||
const cache = {}; | ||
async function findOne(query, sort) { | ||
@@ -229,38 +219,21 @@ let res = me.model.findOne(query); | ||
} | ||
// res = await res; | ||
// if (slugsUpd.length && sort) { | ||
// let field = _.first(_.keys(sort)); | ||
// let top = _.maxBy(slugsUpd, u => { | ||
// return extractCounter(_.get(u, field), options.separator); | ||
// }); | ||
// if (_.has(top, field)) { | ||
// let localCounter = extractCounter( | ||
// _.get(top, field), | ||
// options.separator | ||
// ); | ||
// let dbCounter = extractCounter(res.get(field), options.separator); | ||
// if (localCounter > dbCounter) res = top; | ||
// } | ||
// } | ||
return res; | ||
} | ||
for (let i = 0; i < docs.length; i++) { | ||
let currentUnwoundFields = unwindSlugs(docs[i], unwoundSlugs); | ||
const currentUnwoundFields = unwindSlugs(docs[i], unwoundSlugs); | ||
let actualSlugs = currentUnwoundFields; | ||
if (involvedValuesDocs && involvedValuesDocs.length) { | ||
let actualUpdFields = _(updFields) | ||
.filter(f => { | ||
return _.get(doc, f) != _.get(involvedValuesDocs[i], f); | ||
}) | ||
.map(f => _.trim(f.replace(/\["?(.+?)"?\]/g, '.$1'), '.')) | ||
const actualUpdFields = _(updFields) | ||
.filter((f) => _.get(doc, f) != _.get(involvedValuesDocs[i], f)) | ||
.map((f) => _.trim(f.replace(/\["?(.+?)"?\]/g, '.$1'), '.')) | ||
.value(); | ||
actualSlugs = _.filter(currentUnwoundFields, s => { | ||
return _.intersection( | ||
_.map(s.fields.concat(s.uniqueGroupFields || []), p => | ||
p.replace(/^\//, '') | ||
), | ||
actualUpdFields | ||
).length; | ||
}); | ||
actualSlugs = _.filter( | ||
currentUnwoundFields, | ||
(s) => | ||
_.intersection( | ||
_.map(s.fields.concat(s.uniqueGroupFields || []), (p) => p.replace(/^\//, '')), | ||
actualUpdFields, | ||
).length, | ||
); | ||
} | ||
@@ -270,11 +243,24 @@ if (actualSlugs.length) { | ||
} | ||
slugsUpd[i] = _.cloneDeep(upd.$set || upd); | ||
actualSlugs.forEach(slug => { | ||
let slugVal = _.get(docs[i], slug.path); | ||
slugsUpd[i] = {}; | ||
const origUpd = | ||
_.reduce( | ||
upd.$set, | ||
(r, v, k) => { | ||
_.set(r, k, v); | ||
return r; | ||
}, | ||
{}, | ||
) || upd; | ||
// console.log('actualSlugs', actualSlugs); | ||
// console.log(`docs[${i}]`, docs[i]); | ||
actualSlugs.forEach((slug) => { | ||
const slugVal = _.get(docs[i], slug.path); | ||
if (slugVal != undefined) _.set(slugsUpd[i], slug.path, slugVal); | ||
}); | ||
// console.log('1)slugsUpd[i]', slugsUpd[i]); | ||
if (involvedValuesDocs && involvedValuesDocs.length) { | ||
_.each(currentUnwoundFields, us => { | ||
if (_.get(slugsUpd[i], us.path) === undefined) { | ||
let val = _.get(involvedValuesDocs[i], us.path); | ||
_.each(currentUnwoundFields, (us) => { | ||
// console.log('us.path?', us.path); | ||
if (!_.has(origUpd, us.path) && !_.has(slugsUpd[i], us.path)) { | ||
const val = _.get(involvedValuesDocs[i], us.path); | ||
if (val !== undefined) _.set(slugsUpd[i], us.path, val); | ||
@@ -284,10 +270,12 @@ } | ||
} | ||
// console.log('2)slugsUpd[i]', slugsUpd[i]); | ||
let doUpd = slugsUpd[i]; | ||
// console.log('doUpd', doUpd); | ||
if (upd.$set) { | ||
let slugPaths = _(slugsUpd[i]) | ||
const slugPaths = _(doUpd) | ||
.indexate({ leafsOnly: true }) | ||
// .mapValues(v=>_.isArray(v)?[]:(_.isObject(v)?{}:v)) | ||
.mapKeys((v, f) => _.trim(f.replace(/\["?(.+?)"?\]/g, '.$1'), '.')) | ||
.omitBy(v=>v===undefined) | ||
.omitBy((v) => v === undefined) | ||
.value(); | ||
@@ -298,3 +286,4 @@ doUpd = { $set: slugPaths }; | ||
if (docs.length == 1) { | ||
if (slugsUpd[i]) me[operation]({}, doUpd); | ||
if (doUpd) me[operation]({}, _.merge(me.getUpdate(), doUpd)); | ||
// console.log(me.getQuery(), me.getUpdate()); | ||
} else { | ||
@@ -311,6 +300,5 @@ // Mongoose doesn't support docs without _id | ||
} | ||
// console.log(me.getUpdate()); | ||
} | ||
schema.pre('save', async function() { | ||
let cache = {}; | ||
const cache = {}; | ||
let doc = this; | ||
@@ -322,4 +310,4 @@ if (!doc.model) { | ||
// console.log(doc); | ||
let reSlug = false; | ||
let unwoundSlugs = unwindSlugs(doc, _.filter(slugs, 'on.save')); | ||
const reSlug = false; | ||
const unwoundSlugs = unwindSlugs(doc, _.filter(slugs, 'on.save')); | ||
@@ -339,3 +327,3 @@ if (!unwoundSlugs.length) { | ||
}, | ||
cache | ||
cache, | ||
); | ||
@@ -345,11 +333,14 @@ // console.log(doc); | ||
}; | ||
function updateUpdCache(cache, path, slug, value) { | ||
function updateUpdCache(cache, path, slug, value, group) { | ||
// console.log(`updateUpdCache ${path}: ${slug}`); | ||
let maskedPath = path.replace(/\.[$\d]+\./g, '.$.'); | ||
let isArrayPath = path != maskedPath; | ||
const maskedPath = path.replace(/\.[$\d]+\./g, '.$.'); | ||
const isArrayPath = path != maskedPath; | ||
const localKey = `${maskedPath}:${slug}`; | ||
if (isArrayPath) { | ||
let localKey = maskedPath + ':' + slug; | ||
// console.log(`${path} resolves ${cache.upd[localKey].ext.path} with ${value} \n${localKey}`); | ||
cache.lock[path].ext.resolveEx(value); | ||
delete cache.lock[path]; | ||
} else { | ||
const key = `${localKey}-${JSON.stringify(group)}`; | ||
cache.db[key] = value; | ||
} | ||
@@ -366,26 +357,19 @@ } | ||
findOne, | ||
//slugsMdfPaths | ||
// slugsMdfPaths | ||
) { | ||
// console.log(`findSame#${doc.n} ${path}: ${slug}`); | ||
// console.log(cache); | ||
cache = _.merge(cache, { db: {}, unwind: {}, upd: {}, lock:{} }); | ||
cache = _.merge(cache, { db: {}, unwind: {}, upd: {}, lock: {} }); | ||
// console.log(cache); | ||
let maskedPath = path.replace(/\.[$\d]+\./g, '.$.'); | ||
let isArrayPath = path != maskedPath; | ||
let slugRx = new RegExp( | ||
'^' + | ||
slug + | ||
'(' + | ||
options.separator + | ||
(isCounter ? '(\\d+)' : '(.+)') + | ||
')?$' | ||
); | ||
let localKey = maskedPath + ':' + slug; | ||
// console.log(`findSame#${doc.n} localKey: \n${localKey}`); | ||
let key = localKey + '-' + JSON.stringify(group); | ||
const maskedPath = path.replace(/\.[$\d]+\./g, '.$.'); | ||
const isArrayPath = path != maskedPath; | ||
const slugRx = new RegExp(`^${slug}(${options.separator}${isCounter ? '(\\d+)' : '(.+)'})?$`); | ||
const localKey = `${maskedPath}:${slug}`; | ||
const key = `${localKey}-${JSON.stringify(group)}`; | ||
// console.log(`findSame#${doc.n} key: \n${key}`, cache); | ||
// let candidates = []; | ||
if (isArrayPath) { | ||
// console.log('array? maskedPath', maskedPath); | ||
let ext = { path }; | ||
let updPromise = new Promise((resolve, reject) => { | ||
const ext = { path }; | ||
const updPromise = new Promise((resolve, reject) => { | ||
ext.resolveEx = resolve; | ||
@@ -399,3 +383,3 @@ ext.rejectEx = reject; | ||
cache.upd[localKey] = updPromise; | ||
let fromPath = res.ext.path; | ||
const fromPath = res.ext.path; | ||
cache.lock[path] = updPromise; | ||
@@ -406,45 +390,25 @@ // console.log(`${path} waits for ${fromPath} \n${localKey}`); | ||
return res; | ||
} else { | ||
// console.log(`${path} put lock init \n${localKey}`); | ||
cache.upd[localKey] = updPromise; | ||
cache.lock[path] = updPromise; | ||
} | ||
// if (cache.unwind[maskedPath] === undefined) { | ||
// cache.unwind[maskedPath] = { | ||
// list: _(unwindPath(doc, maskedPath)) | ||
// .map(p => [p, docGet(doc, p)]) | ||
// .filter(([p, v]) => v !== undefined && slugsMdfPaths[p] === undefined) | ||
// .sortBy('[1]') | ||
// .value(), | ||
// }; | ||
// } | ||
// | ||
// let top = _(cache.unwind[maskedPath].list) | ||
// .filter(([p, v]) => p != path && v.match(slugRx)) | ||
// .last(); | ||
// if (top) { | ||
// // console.log(`unwind cache for ${path}: ${top[1]}`); | ||
// candidates.push(top[1]); | ||
// } else { | ||
// console.log(`no unwind cache for ${path}: `,cache.unwind[maskedPath].list); | ||
// } | ||
// console.log(`${path} put lock init \n${localKey}`); | ||
cache.upd[localKey] = updPromise; | ||
cache.lock[path] = updPromise; | ||
} | ||
let query = _.cloneDeep(group); | ||
let sort = {}; | ||
const sort = {}; | ||
if (cache.db[key] === undefined) { | ||
let arrayPath = path.replace(/\.[$\d]+\./g, '.'); | ||
const arrayPath = path.replace(/\.[$\d]+\./g, '.'); | ||
query[arrayPath] = slugRx; | ||
if (doc._id) { | ||
if(query['_id']==undefined){ | ||
query['_id'] = { | ||
if (query._id == undefined) { | ||
query._id = { | ||
$ne: doc._id, | ||
}; | ||
}else{ | ||
query=false; | ||
} else { | ||
query = false; | ||
} | ||
} | ||
if(query!==false){ | ||
if (query !== false) { | ||
if (isCounter) sort[arrayPath] = -1; | ||
cache.db[key] = findOne(query, sort); | ||
}else{ | ||
} else { | ||
cache.db[key] = null; | ||
@@ -461,3 +425,3 @@ } | ||
foundDoc = _(unwindPath(foundDoc, maskedPath)) | ||
.map(p => [p, docGet(foundDoc, p)]) | ||
.map((p) => [p, docGet(foundDoc, p)]) | ||
.filter(([p, v]) => v.match(slugRx)) | ||
@@ -475,4 +439,4 @@ .sortBy('[1]') | ||
// if (cache.db[key] !== undefined) { | ||
// console.log(`db cache for ${path}: ${cache.db[key]}`); | ||
// candidates.push(cache.db[key]); | ||
// console.log(`db cache for ${path}: ${cache.db[key]}`); | ||
// candidates.push(cache.db[key]); | ||
// } | ||
@@ -487,15 +451,12 @@ | ||
} | ||
let docGet = (doc, path) => | ||
_.isFunction(doc.get) ? doc.get(path) : _.get(doc, path); | ||
let docSet = (doc, path, val) => | ||
let docGet = (doc, path) => (_.isFunction(doc.get) ? doc.get(path) : _.get(doc, path)); | ||
const docSet = (doc, path, val) => | ||
_.isFunction(doc.set) ? doc.set(path, val) : _.set(doc, path, val); | ||
let docIsModified = (doc, path) => | ||
_.isFunction(doc.isModified) | ||
? doc.isModified(path) | ||
: _.get(doc, path) !== undefined; | ||
const docIsModified = (doc, path) => | ||
_.isFunction(doc.isModified) ? doc.isModified(path) : _.get(doc, path) !== undefined; | ||
function unwindSlugs(doc, slugs) { | ||
let unwoundSlugs = []; | ||
slugs.forEach(slug => { | ||
let slugPaths = unwindPath(doc, slug.path); | ||
const unwoundSlugs = []; | ||
slugs.forEach((slug) => { | ||
const slugPaths = unwindPath(doc, slug.path); | ||
if (!slugPaths.length) slugPaths.push(slug.path); | ||
@@ -505,3 +466,3 @@ let basePath = slug.basePath; | ||
if (_.endsWith(basePath, '.$')) basePath += '.'; | ||
slugPaths.forEach(slugPath => { | ||
slugPaths.forEach((slugPath) => { | ||
let unwoundBasePath = slugPath.replace(/\.[^\.]+$/, ''); | ||
@@ -531,24 +492,16 @@ if (unwoundBasePath == slugPath) unwoundBasePath = ''; | ||
if (!_.startsWith(fieldPath, '/')) { | ||
fieldPath = | ||
'/' + | ||
((slugValueBasePath && slugValueBasePath + '.') || '') + | ||
fieldPath; | ||
fieldPath = `/${(slugValueBasePath && `${slugValueBasePath}.`) || ''}${fieldPath}`; | ||
} | ||
if (_.startsWith(fieldPath, '/' + originalBasePath)) | ||
fieldPath = fieldPath.replace( | ||
'/' + originalBasePath, | ||
'/' + slugValueBasePath | ||
); | ||
if (_.startsWith(fieldPath, `/${originalBasePath}`)) | ||
fieldPath = fieldPath.replace(`/${originalBasePath}`, `/${slugValueBasePath}`); | ||
return fieldPath; | ||
} | ||
let unwoundFields = slug.fields.map(unwindFieldPath); | ||
let unwoundGroupPaths = (slug.uniqueGroupFields || []).map( | ||
unwindFieldPath | ||
); | ||
const unwoundFields = slug.fields.map(unwindFieldPath); | ||
const unwoundGroupPaths = (slug.uniqueGroupFields || []).map(unwindFieldPath); | ||
if ( | ||
_.some(unwoundFields.concat(unwoundGroupPaths), path => { | ||
return docIsModified(doc, path.replace(/^\//, '')); | ||
}) | ||
_.some(unwoundFields.concat(unwoundGroupPaths), (path) => | ||
docIsModified(doc, path.replace(/^\//, '')), | ||
) | ||
) { | ||
let s = _.cloneDeep(slug); | ||
const s = _.cloneDeep(slug); | ||
s.path = slugPath; | ||
@@ -573,12 +526,10 @@ s.basePath = unwoundBasePath; | ||
let res = []; | ||
let value = docGet(doc, path); | ||
const value = docGet(doc, path); | ||
if (_.isArray(value)) { | ||
for (let i = 0; i < value.length; i++) { | ||
let childPath = path + '.' + i + '.' + restPathParts[0]; | ||
const childPath = `${path}.${i}.${restPathParts[0]}`; | ||
res = res.concat(unwindPath(doc, childPath, _.drop(restPathParts))); | ||
} | ||
} else { | ||
if (!restPathParts || !restPathParts.length) res.push(path); | ||
} | ||
} else if (!restPathParts || !restPathParts.length) res.push(path); | ||
return res; | ||
@@ -594,9 +545,9 @@ } | ||
await Promise.all( | ||
slugs.map(async slug => { | ||
var fields = []; | ||
slugs.map(async (slug) => { | ||
const fields = []; | ||
slug.fields.forEach(slugField => { | ||
slug.fields.forEach((slugField) => { | ||
fields.push(docGet(doc, slugField.replace(/^\//, ''))); | ||
}); | ||
let oldSlug = docGet(doc, slug.path); | ||
const oldSlug = docGet(doc, slug.path); | ||
if ( | ||
@@ -609,7 +560,6 @@ !(slug.unique || slug.uniqueSlug) && | ||
} | ||
return; | ||
} else { | ||
var query = {}; | ||
const query = {}; | ||
if (slug.uniqueGroupFields) { | ||
slug.uniqueGroupFields.forEach(function(fieldName) { | ||
slug.uniqueGroupFields.forEach((fieldName) => { | ||
fieldName = fieldName.replace(/^\//, ''); | ||
@@ -619,3 +569,3 @@ query[fieldName] = docGet(doc, fieldName); | ||
} | ||
if (!docGet(doc,slug.path) || !slug.permanent) { | ||
if (!docGet(doc, slug.path) || !slug.permanent) { | ||
if (slug.isShortIdMode) { | ||
@@ -634,4 +584,4 @@ docSet( | ||
cache, | ||
//slugsMdfPaths | ||
) | ||
// slugsMdfPaths | ||
), | ||
); | ||
@@ -651,4 +601,4 @@ } else { | ||
cache, | ||
//slugsMdfPaths | ||
) | ||
// slugsMdfPaths | ||
), | ||
); | ||
@@ -658,3 +608,3 @@ } | ||
} | ||
}) | ||
}), | ||
); | ||
@@ -665,3 +615,3 @@ return doc; | ||
function makeSlug(values, options) { | ||
var slug = getSlug(values.join(' '), options); | ||
const slug = getSlug(values.join(' '), options); | ||
@@ -671,6 +621,8 @@ return slug; | ||
function extractCounter(value, separator) { | ||
let count = 0, | ||
test = new RegExp(separator + '(\\d+)$'), | ||
match = null; | ||
let count = 0; | ||
const test = new RegExp(`${separator}(\\d+)$`); | ||
let match = null; | ||
if ((match = value.match(test))) { | ||
@@ -691,9 +643,9 @@ count = match[1]; | ||
cache, | ||
//slugsMdfPaths | ||
// slugsMdfPaths | ||
) { | ||
let slug = makeSlug(values, options); | ||
let originalSlug = slug; | ||
const originalSlug = slug; | ||
let count = 0; | ||
let result = await findSame( | ||
const result = await findSame( | ||
cache, | ||
@@ -707,3 +659,3 @@ doc, | ||
findOne, | ||
//slugsMdfPaths | ||
// slugsMdfPaths | ||
); | ||
@@ -714,3 +666,3 @@ if (result) { | ||
} | ||
updateUpdCache(cache, path, originalSlug, slug); | ||
updateUpdCache(cache, path, originalSlug, slug, groups); | ||
// console.log('after cache', cache); | ||
@@ -729,8 +681,8 @@ return slug; | ||
cache, | ||
//slugsMdfPaths | ||
// slugsMdfPaths | ||
) { | ||
let slug = makeSlug(values, options); | ||
let originalSlug = slug; | ||
const originalSlug = slug; | ||
let result = await findSame( | ||
const result = await findSame( | ||
cache, | ||
@@ -744,11 +696,11 @@ doc, | ||
findOne, | ||
//slugsMdfPaths | ||
// slugsMdfPaths | ||
); | ||
if (result) { | ||
// console.log(`slug already exists at ${path}`, result); | ||
let oldSlug = docGet(doc, path); | ||
const oldSlug = docGet(doc, path); | ||
if ( | ||
//reuse old slug if possible | ||
// reuse old slug if possible | ||
oldSlug && | ||
oldSlug.match(new RegExp('^' + slug + options.separator + '.*$')) | ||
oldSlug.match(new RegExp(`^${slug}${options.separator}.*$`)) | ||
) { | ||
@@ -758,10 +710,8 @@ // console.log("reuse old random slug",doc[path]); | ||
} else slug += options.separator + shortId.generate(); | ||
} else { | ||
if (forceShortId) { | ||
slug += options.separator + shortId.generate(); | ||
} | ||
} else if (forceShortId) { | ||
slug += options.separator + shortId.generate(); | ||
} | ||
updateUpdCache(cache, path, originalSlug, slug); | ||
updateUpdCache(cache, path, originalSlug, slug, groups); | ||
// console.log('after cache', cache); | ||
return slug; | ||
} |
{ | ||
"name": "mongoose-slug-updater", | ||
"version": "3.1.0", | ||
"version": "3.1.1", | ||
"description": "Schema-based slug plugin for Mongoose - single/compound - unique over collection/group - nested docs/arrays - relative/abs paths - sync on change: create/save/update/updateOne/updateMany/findOneAndUpdate tracked - $set operator - counter/shortId", | ||
@@ -17,2 +17,3 @@ "main": "index.js", | ||
"devext": "nodemon ./node_modules/.bin/mocha --reporter min -g '.*external.*' --no-deprecation", | ||
"devbugs": "nodemon ./node_modules/.bin/mocha --reporter min -g 'UpdateOne nested docs declared in extrenal schemas' --no-deprecation", | ||
"devcounter": "nodemon ./node_modules/.bin/mocha --reporter min -g '.*counter.*' --no-deprecation" | ||
@@ -19,0 +20,0 @@ }, |
@@ -13,5 +13,5 @@ // https://github.com/YuriGor/mongoose-slug-updater/issues/7 | ||
const slugGenerator = require('../../.'); | ||
// const slugGenerator = require('../../.'); | ||
mongoose.plugin(slugGenerator); | ||
// mongoose.plugin(slugGenerator); | ||
@@ -46,7 +46,10 @@ const ProductSchema = new mongoose.Schema({ | ||
doc.should.have.property('other_image_ids').and.deep.equal([{ name: 'imagename' }]); | ||
// console.log('before findOneAndUpdate'); | ||
doc = await Product.findOneAndUpdate( | ||
{ _id: doc.id }, | ||
{ name: 'test1', other_image_ids: [{ name: 'imagename1' }] }, | ||
{ $set: { name: 'test1', other_image_ids: [{ name: 'imagename1' }] } }, | ||
{ new: true }, | ||
); | ||
doc.should.have.property('name').and.equal('test1'); | ||
@@ -63,3 +66,13 @@ doc.should.have.property('slug').and.equal('test1'); | ||
doc.should.have.property('other_image_ids').and.deep.equal([{ name: 'imagename2' }]); | ||
doc = await Product.findOneAndUpdate( | ||
{ _id: doc.id }, | ||
{ name: 'test3', other_image_ids: [{ name: 'imagename3' }] }, | ||
{ new: true }, | ||
); | ||
doc.should.have.property('name').and.equal('test3'); | ||
doc.should.have.property('slug').and.equal('test3'); | ||
doc.should.have.property('other_image_ids').and.deep.equal([{ name: 'imagename3' }]); | ||
}); | ||
}); |
@@ -1,8 +0,9 @@ | ||
'use strict'; | ||
const mongoose = require('mongoose'); | ||
const mongoose = require('mongoose'), | ||
chai = require('chai'), | ||
should = chai.should(), | ||
assert = require('assert'); | ||
const chai = require('chai'); | ||
const should = chai.should(); | ||
const assert = require('assert'); | ||
const { ShortId, Counter } = require('./../model'); | ||
@@ -12,3 +13,3 @@ | ||
describe('findOneAndUpdate', function() { | ||
describe('findOneAndUpdate', () => { | ||
beforeEach(async () => { | ||
@@ -26,3 +27,3 @@ await ShortId.remove({}); | ||
// console.log(' --- findOneAndUpdate --- '); | ||
let doc = await ShortId.findOneAndUpdate( | ||
const doc = await ShortId.findOneAndUpdate( | ||
{ title: 'impossible' }, | ||
@@ -34,3 +35,3 @@ { | ||
}, | ||
{ upsert: true, new: true } | ||
{ upsert: true, new: true }, | ||
); | ||
@@ -40,3 +41,3 @@ // console.log(doc); | ||
doc.should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
let { _id } = doc; | ||
const { _id } = doc; | ||
let mdf = { | ||
@@ -56,7 +57,3 @@ otherField: tellme.getText(3), | ||
editedDoc = await ShortId.findOneAndUpdate( | ||
{ _id }, | ||
{ $set: mdf }, | ||
{ new: true } | ||
); | ||
editedDoc = await ShortId.findOneAndUpdate({ _id }, { $set: mdf }, { new: true }); | ||
@@ -70,3 +67,3 @@ editedDoc.should.have.property('otherField').and.equal(mdf.otherField); | ||
it('Update not watcher field counter', async () => { | ||
let doc = await Counter.findOneAndUpdate( | ||
const doc = await Counter.findOneAndUpdate( | ||
{ title: 'impossible' }, | ||
@@ -78,3 +75,3 @@ { | ||
}, | ||
{ upsert: true, new: true } | ||
{ upsert: true, new: true }, | ||
); | ||
@@ -84,3 +81,3 @@ doc.should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
let { _id } = doc; | ||
const { _id } = doc; | ||
let mdf = { | ||
@@ -99,7 +96,3 @@ otherField: tellme.getText(3), | ||
}; | ||
editedDoc = await Counter.findOneAndUpdate( | ||
{ _id }, | ||
{ $set: mdf }, | ||
{ new: true } | ||
); | ||
editedDoc = await Counter.findOneAndUpdate({ _id }, { $set: mdf }, { new: true }); | ||
@@ -113,3 +106,3 @@ editedDoc.should.have.property('otherField').and.equal(mdf.otherField); | ||
it('Update title and check if slug was updated', async () => { | ||
let doc = await ShortId.findOneAndUpdate( | ||
const doc = await ShortId.findOneAndUpdate( | ||
{ title: 'impossible' }, | ||
@@ -120,7 +113,7 @@ { | ||
}, | ||
{ upsert: true, new: true } | ||
{ upsert: true, new: true }, | ||
); | ||
doc.should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
doc.should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
let { _id } = doc; | ||
const { _id } = doc; | ||
let mdf = { | ||
@@ -140,7 +133,3 @@ title: tellme.getText(2), | ||
// console.debug('upd_id', _id); | ||
editedDoc = await ShortId.findOneAndUpdate( | ||
{ _id }, | ||
{ $set: mdf }, | ||
{ new: true } | ||
); | ||
editedDoc = await ShortId.findOneAndUpdate({ _id }, { $set: mdf }, { new: true }); | ||
@@ -152,3 +141,3 @@ editedDoc.should.have.property('slug').and.equal(tellme.getSlug(3, 1)); | ||
it('Update subtitle and check if slug was updated', async () => { | ||
let doc = await ShortId.findOneAndUpdate( | ||
const doc = await ShortId.findOneAndUpdate( | ||
{ title: 'impossible' }, | ||
@@ -159,7 +148,7 @@ { | ||
}, | ||
{ upsert: true, new: true } | ||
{ upsert: true, new: true }, | ||
); | ||
doc.should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
doc.should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
let { _id } = doc; | ||
const { _id } = doc; | ||
let mdf = { | ||
@@ -176,7 +165,3 @@ subtitle: tellme.getText(2), | ||
// console.debug('upd_id', _id); | ||
editedDoc = await ShortId.findOneAndUpdate( | ||
{ _id }, | ||
{ $set: mdf }, | ||
{ new: true } | ||
); | ||
editedDoc = await ShortId.findOneAndUpdate({ _id }, { $set: mdf }, { new: true }); | ||
@@ -188,3 +173,3 @@ editedDoc.should.have.property('slug').and.equal(tellme.getSlug(0, 3)); | ||
it("Update watcher fields to the same values and check slugs wasn't changed", async () => { | ||
let doc = await ShortId.findOneAndUpdate( | ||
const doc = await ShortId.findOneAndUpdate( | ||
{ title: 'impossible' }, | ||
@@ -195,8 +180,8 @@ { | ||
}, | ||
{ upsert: true, new: true } | ||
{ upsert: true, new: true }, | ||
); | ||
doc.should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
doc.should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
let { _id } = doc; | ||
let mdf = { | ||
const { _id } = doc; | ||
const mdf = { | ||
title: tellme.getText(0), | ||
@@ -211,7 +196,3 @@ subtitle: tellme.getText(1), | ||
editedDoc = await ShortId.findOneAndUpdate( | ||
{ _id }, | ||
{ $set: mdf }, | ||
{ new: true } | ||
); | ||
editedDoc = await ShortId.findOneAndUpdate({ _id }, { $set: mdf }, { new: true }); | ||
@@ -223,3 +204,3 @@ doc.should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
it('UpdateOne without _id', async () => { | ||
let doc = await ShortId.findOneAndUpdate( | ||
const doc = await ShortId.findOneAndUpdate( | ||
{ title: 'impossible' }, | ||
@@ -230,3 +211,3 @@ { | ||
}, | ||
{ upsert: true, new: true } | ||
{ upsert: true, new: true }, | ||
); | ||
@@ -241,9 +222,5 @@ doc.should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
let editedDoc = await ShortId.findOneAndUpdate( | ||
{ uniqueSlug: tellme.getSlug(0) }, | ||
mdf, | ||
{ | ||
new: true, | ||
} | ||
); | ||
let editedDoc = await ShortId.findOneAndUpdate({ uniqueSlug: tellme.getSlug(0) }, mdf, { | ||
new: true, | ||
}); | ||
@@ -263,3 +240,3 @@ editedDoc.should.have.property('slug').and.equal(tellme.getSlug(2, 3)); | ||
{ $set: mdf }, | ||
{ new: true } | ||
{ new: true }, | ||
); | ||
@@ -266,0 +243,0 @@ |
@@ -1,8 +0,9 @@ | ||
'use strict'; | ||
const mongoose = require('mongoose'); | ||
const mongoose = require('mongoose'), | ||
chai = require('chai'), | ||
should = chai.should(), | ||
assert = require('assert'); | ||
const chai = require('chai'); | ||
const should = chai.should(); | ||
const assert = require('assert'); | ||
const { nIterations, ShortId, Counter } = require('./../model'); | ||
@@ -12,3 +13,3 @@ | ||
describe('update', function() { | ||
describe('update', () => { | ||
beforeEach(async () => { | ||
@@ -25,3 +26,3 @@ await ShortId.remove({}); | ||
it('Update not watcher field shortId', async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
@@ -31,3 +32,3 @@ subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
@@ -59,3 +60,3 @@ otherField: tellme.getText(1), | ||
it('Update not watcher field counter', async () => { | ||
let res = await Counter.create({ | ||
const res = await Counter.create({ | ||
title: tellme.getText(0), | ||
@@ -65,3 +66,3 @@ subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
@@ -93,7 +94,7 @@ otherField: tellme.getText(1), | ||
it('Update title and check if slug was updated', async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
@@ -122,3 +123,3 @@ title: tellme.getText(2), | ||
it('Update subtitle and check if slug was updated', async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
@@ -128,3 +129,3 @@ subtitle: tellme.getText(1), | ||
// console.debug('created doc', res); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
@@ -150,8 +151,8 @@ subtitle: tellme.getText(3), | ||
it("Update watcher fields to the same values and check slugs wasn't changed", async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
const { _id, slug, uniqueSlug } = res; | ||
const mdf = { | ||
title: tellme.getText(0), | ||
@@ -172,3 +173,3 @@ subtitle: tellme.getText(1), | ||
it('UpdateOne without _id', async () => { | ||
let doc = await ShortId.create({ | ||
const doc = await ShortId.create({ | ||
title: tellme.getText(0), | ||
@@ -213,13 +214,8 @@ subtitle: tellme.getText(1), | ||
docs[i].should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
if (i) | ||
docs[i].should.have | ||
.property('uniqueSlug') | ||
.and.match(tellme.getShortRegex(0)); | ||
else | ||
docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
if (i) docs[i].should.have.property('uniqueSlug').and.match(tellme.getShortRegex(0)); | ||
else docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
} | ||
await ShortId.updateMany( | ||
{ otherField: { $gt: 4 } }, | ||
{ title: tellme.getText(1) } | ||
); | ||
// console.log(' ---- updateMany'); | ||
await ShortId.updateMany({ otherField: { $gt: 4 } }, { title: tellme.getText(1) }); | ||
// console.log(' ---- updateMany done'); | ||
@@ -229,5 +225,3 @@ docs = ShortId.find({ otherField: { $lt: 5 } }); | ||
docs[i].should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
docs[i].should.have | ||
.property('uniqueSlug') | ||
.and.match(tellme.getShortRegex(0)); | ||
docs[i].should.have.property('uniqueSlug').and.match(tellme.getShortRegex(0)); | ||
} | ||
@@ -238,8 +232,4 @@ | ||
docs[i].should.have.property('slug').and.equal(tellme.getSlug(2, 1)); | ||
if (i) | ||
docs[i].should.have | ||
.property('uniqueSlug') | ||
.and.match(tellme.getShortRegex(2)); | ||
else | ||
docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(2)); | ||
if (i) docs[i].should.have.property('uniqueSlug').and.match(tellme.getShortRegex(2)); | ||
else docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(2)); | ||
} | ||
@@ -257,13 +247,6 @@ }); | ||
docs[i].should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
if (i) | ||
docs[i].should.have | ||
.property('uniqueSlug') | ||
.and.equal(tellme.getCounterSlug(0, i)); | ||
else | ||
docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
if (i) docs[i].should.have.property('uniqueSlug').and.equal(tellme.getCounterSlug(0, i)); | ||
else docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
} | ||
await Counter.updateMany( | ||
{ otherField: { $gt: 4 } }, | ||
{ title: tellme.getText(1) } | ||
); | ||
await Counter.updateMany({ otherField: { $gt: 4 } }, { title: tellme.getText(1) }); | ||
@@ -273,8 +256,4 @@ docs = Counter.find({ otherField: { $lt: 5 } }); | ||
docs[i].should.have.property('slug').and.equal(tellme.getSlug(0, 1)); | ||
if (i) | ||
docs[i].should.have | ||
.property('uniqueSlug') | ||
.and.equal(tellme.getCounterSlug(0, i)); | ||
else | ||
docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
if (i) docs[i].should.have.property('uniqueSlug').and.equal(tellme.getCounterSlug(0, i)); | ||
else docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(0)); | ||
} | ||
@@ -285,12 +264,6 @@ | ||
docs[i].should.have.property('slug').and.equal(tellme.getSlug(2, 1)); | ||
if(i) | ||
docs[i].should.have | ||
.property('uniqueSlug') | ||
.and.equal(tellme.getCounterSlug(2,i)); | ||
else | ||
docs[i].should.have | ||
.property('uniqueSlug') | ||
.and.equal(tellme.getSlug(2)); | ||
if (i) docs[i].should.have.property('uniqueSlug').and.equal(tellme.getCounterSlug(2, i)); | ||
else docs[i].should.have.property('uniqueSlug').and.equal(tellme.getSlug(2)); | ||
} | ||
}); | ||
}); |
@@ -1,8 +0,9 @@ | ||
'use strict'; | ||
const mongoose = require('mongoose'); | ||
const mongoose = require('mongoose'), | ||
chai = require('chai'), | ||
should = chai.should(), | ||
assert = require('assert'); | ||
const chai = require('chai'); | ||
const should = chai.should(); | ||
const assert = require('assert'); | ||
const { ShortId, Counter } = require('./../model'); | ||
@@ -12,3 +13,4 @@ | ||
const { nIterations } = require('./../options'); | ||
describe('updateOne', function() { | ||
describe('updateOne', () => { | ||
beforeEach(async () => { | ||
@@ -25,3 +27,3 @@ await ShortId.remove({}); | ||
it('Update not watcher field shortId', async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
@@ -31,3 +33,3 @@ subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
res.should.have | ||
@@ -63,3 +65,3 @@ .property('forcedSlug') | ||
it('Update not watcher field counter', async () => { | ||
let res = await Counter.create({ | ||
const res = await Counter.create({ | ||
title: tellme.getText(0), | ||
@@ -69,3 +71,3 @@ subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
@@ -97,7 +99,7 @@ otherField: tellme.getText(1), | ||
it('Update title and check if slug was updated', async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
@@ -126,3 +128,3 @@ title: tellme.getText(2), | ||
it('Update subtitle and check if slug was updated', async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
@@ -136,3 +138,3 @@ subtitle: tellme.getText(1), | ||
// console.debug('created doc', res); | ||
let { _id, slug, uniqueSlug } = res; | ||
const { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
@@ -167,8 +169,8 @@ subtitle: tellme.getText(3), | ||
it("Update watcher fields to the same values and check slugs wasn't changed", async () => { | ||
let res = await ShortId.create({ | ||
const res = await ShortId.create({ | ||
title: tellme.getText(0), | ||
subtitle: tellme.getText(1), | ||
}); | ||
let { _id, slug, uniqueSlug } = res; | ||
let mdf = { | ||
const { _id, slug, uniqueSlug } = res; | ||
const mdf = { | ||
title: tellme.getText(0), | ||
@@ -189,7 +191,7 @@ subtitle: tellme.getText(1), | ||
it("Update watcher fields to the same values and check counter wasn't changed", async () => { | ||
let mdf = { | ||
const mdf = { | ||
title: tellme.getText(0), | ||
subtitle: tellme.getText(1), | ||
}; | ||
let docs = []; | ||
const docs = []; | ||
for (let i = 0; i < nIterations; i++) { | ||
@@ -201,8 +203,8 @@ docs[i] = await Counter.create(mdf); | ||
for (let i = 1; i < nIterations; i++) { | ||
docs[i].should.have.property('title').and.equal(tellme.getText(0)); | ||
docs[i].should.have.property('uniqueSlug').and.equal(tellme.getCounterSlug(0, i)); | ||
docs[i].should.have.property('title').and.equal(tellme.getText(0)); | ||
docs[i].should.have.property('uniqueSlug').and.equal(tellme.getCounterSlug(0, i)); | ||
} | ||
for (let i = 0; i < nIterations; i++) { | ||
await Counter.updateOne({_id:docs[i]._id},mdf); | ||
await Counter.updateOne({ _id: docs[i]._id }, mdf); | ||
docs[i] = await Counter.findById(docs[i]._id); | ||
@@ -217,8 +219,6 @@ } | ||
} | ||
}); | ||
it('UpdateOne without _id', async () => { | ||
let doc = await ShortId.create({ | ||
const doc = await ShortId.create({ | ||
title: tellme.getText(0), | ||
@@ -225,0 +225,0 @@ subtitle: tellme.getText(1), |
@@ -1,21 +0,16 @@ | ||
'use strict'; | ||
const _ = require('lodash'); | ||
const _ = require('lodash'), | ||
mongoose = require('mongoose'), | ||
chai = require('chai'), | ||
should = chai.should(), | ||
assert = require('assert'); | ||
const mongoose = require('mongoose'); | ||
const { | ||
nIterations, | ||
SubChild, | ||
Child, | ||
Parent, | ||
SimpleChild, | ||
SimpleParent, | ||
} = require('./../model'); | ||
const chai = require('chai'); | ||
const should = chai.should(); | ||
const assert = require('assert'); | ||
const { nIterations, SubChild, Child, Parent, SimpleChild, SimpleParent } = require('./../model'); | ||
const tellme = require('./../tellme'); | ||
describe('Nested Docs', function() { | ||
describe('Nested Docs', () => { | ||
beforeEach(async () => { | ||
@@ -32,3 +27,3 @@ await Parent.remove({}); | ||
it('Save simple nested doc declared in extrenal schemas', async () => { | ||
let doc = await SimpleParent.create({ | ||
const doc = await SimpleParent.create({ | ||
title: tellme.getText(0), | ||
@@ -48,9 +43,7 @@ child: { | ||
doc.should.have.nested.property('child.slug').and.equal(tellme.getSlug(1)); | ||
doc.should.have.nested | ||
.property('children.0.slug') | ||
.and.equal(tellme.getSlug(2)); | ||
doc.should.have.nested.property('children.0.slug').and.equal(tellme.getSlug(2)); | ||
}); | ||
it('Save nested doc declared in extrenal schemas', async () => { | ||
let docCfg = Parent.getNewDoc(); | ||
const docCfg = Parent.getNewDoc(); | ||
@@ -68,7 +61,8 @@ let doc = await Parent.create(docCfg); | ||
await Parent.updateOne({}, Parent.getNewDoc(), { upsert: true }); | ||
let doc = await Parent.findOne({}); | ||
const doc = await Parent.findOne({}); | ||
// console.log('doc', doc); | ||
Parent.testNewDoc(doc); | ||
let mdf = Parent.changeDoc({}); | ||
const mdf = Parent.changeDoc({}); | ||
await Parent.updateOne({ _id: doc._id }, mdf); | ||
let editedDoc = await Parent.findById(doc._id); | ||
const editedDoc = await Parent.findById(doc._id); | ||
Parent.testChangedDoc(editedDoc); | ||
@@ -79,7 +73,7 @@ }); | ||
await Parent.update({}, Parent.getNewDoc(), { upsert: true }); | ||
let doc = await Parent.findOne({}); | ||
const doc = await Parent.findOne({}); | ||
Parent.testNewDoc(doc); | ||
let mdf = Parent.changeDoc({}); | ||
const mdf = Parent.changeDoc({}); | ||
await Parent.update({ _id: doc._id }, mdf); | ||
let editedDoc = await Parent.findById(doc._id); | ||
const editedDoc = await Parent.findById(doc._id); | ||
Parent.testChangedDoc(editedDoc); | ||
@@ -90,7 +84,7 @@ }); | ||
await Parent.updateMany({}, Parent.getNewDoc(), { upsert: true }); | ||
let doc = await Parent.findOne({}); | ||
const doc = await Parent.findOne({}); | ||
Parent.testNewDoc(doc); | ||
let mdf = Parent.changeDoc({}); | ||
const mdf = Parent.changeDoc({}); | ||
await Parent.updateMany({ _id: doc._id }, mdf); | ||
let editedDoc = await Parent.findById(doc._id); | ||
const editedDoc = await Parent.findById(doc._id); | ||
Parent.testChangedDoc(editedDoc); | ||
@@ -100,3 +94,3 @@ }); | ||
it('findOneAndUpdate nested docs declared in extrenal schemas', async () => { | ||
let doc = await Parent.findOneAndUpdate({}, Parent.getNewDoc(), { | ||
const doc = await Parent.findOneAndUpdate({}, Parent.getNewDoc(), { | ||
upsert: true, | ||
@@ -106,4 +100,4 @@ new: true, | ||
Parent.testNewDoc(doc); | ||
let mdf = Parent.changeDoc({}); | ||
let editedDoc = await Parent.findOneAndUpdate({ _id: doc._id }, mdf, { | ||
const mdf = Parent.changeDoc({}); | ||
const editedDoc = await Parent.findOneAndUpdate({ _id: doc._id }, mdf, { | ||
new: true, | ||
@@ -110,0 +104,0 @@ }); |
442774
-0.79%56
-1.75%6076
-1.73%