model.js 173 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const Aggregate = require('./aggregate');
  6. const ChangeStream = require('./cursor/ChangeStream');
  7. const Document = require('./document');
  8. const DocumentNotFoundError = require('./error/notFound');
  9. const DivergentArrayError = require('./error/divergentArray');
  10. const EventEmitter = require('events').EventEmitter;
  11. const MongooseBuffer = require('./types/buffer');
  12. const MongooseError = require('./error/index');
  13. const OverwriteModelError = require('./error/overwriteModel');
  14. const PromiseProvider = require('./promise_provider');
  15. const Query = require('./query');
  16. const RemoveOptions = require('./options/removeOptions');
  17. const SaveOptions = require('./options/saveOptions');
  18. const Schema = require('./schema');
  19. const ServerSelectionError = require('./error/serverSelection');
  20. const ValidationError = require('./error/validation');
  21. const VersionError = require('./error/version');
  22. const ParallelSaveError = require('./error/parallelSave');
  23. const applyQueryMiddleware = require('./helpers/query/applyQueryMiddleware');
  24. const applyHooks = require('./helpers/model/applyHooks');
  25. const applyMethods = require('./helpers/model/applyMethods');
  26. const applyStaticHooks = require('./helpers/model/applyStaticHooks');
  27. const applyStatics = require('./helpers/model/applyStatics');
  28. const applyWriteConcern = require('./helpers/schema/applyWriteConcern');
  29. const assignVals = require('./helpers/populate/assignVals');
  30. const castBulkWrite = require('./helpers/model/castBulkWrite');
  31. const createPopulateQueryFilter = require('./helpers/populate/createPopulateQueryFilter');
  32. const getDefaultBulkwriteResult = require('./helpers/getDefaultBulkwriteResult');
  33. const discriminator = require('./helpers/model/discriminator');
  34. const each = require('./helpers/each');
  35. const get = require('./helpers/get');
  36. const getConstructorName = require('./helpers/getConstructorName');
  37. const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
  38. const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
  39. const immediate = require('./helpers/immediate');
  40. const internalToObjectOptions = require('./options').internalToObjectOptions;
  41. const isDefaultIdIndex = require('./helpers/indexes/isDefaultIdIndex');
  42. const isIndexEqual = require('./helpers/indexes/isIndexEqual');
  43. const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
  44. const leanPopulateMap = require('./helpers/populate/leanPopulateMap');
  45. const modifiedPaths = require('./helpers/update/modifiedPaths');
  46. const parallelLimit = require('./helpers/parallelLimit');
  47. const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscriminatorPipeline');
  48. const removeDeselectedForeignField = require('./helpers/populate/removeDeselectedForeignField');
  49. const setDottedPath = require('./helpers/path/setDottedPath');
  50. const util = require('util');
  51. const utils = require('./utils');
  52. const VERSION_WHERE = 1;
  53. const VERSION_INC = 2;
  54. const VERSION_ALL = VERSION_WHERE | VERSION_INC;
  55. const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
  56. const modelCollectionSymbol = Symbol('mongoose#Model#collection');
  57. const modelDbSymbol = Symbol('mongoose#Model#db');
  58. const modelSymbol = require('./helpers/symbols').modelSymbol;
  59. const subclassedSymbol = Symbol('mongoose#Model#subclassed');
  60. const saveToObjectOptions = Object.assign({}, internalToObjectOptions, {
  61. bson: true
  62. });
  63. /**
  64. * A Model is a class that's your primary tool for interacting with MongoDB.
  65. * An instance of a Model is called a [Document](./api.html#Document).
  66. *
  67. * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model`
  68. * class. You should not use the `mongoose.Model` class directly. The
  69. * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and
  70. * [`connection.model()`](./api.html#connection_Connection-model) functions
  71. * create subclasses of `mongoose.Model` as shown below.
  72. *
  73. * ####Example:
  74. *
  75. * // `UserModel` is a "Model", a subclass of `mongoose.Model`.
  76. * const UserModel = mongoose.model('User', new Schema({ name: String }));
  77. *
  78. * // You can use a Model to create new documents using `new`:
  79. * const userDoc = new UserModel({ name: 'Foo' });
  80. * await userDoc.save();
  81. *
  82. * // You also use a model to create queries:
  83. * const userFromDb = await UserModel.findOne({ name: 'Foo' });
  84. *
  85. * @param {Object} doc values for initial set
  86. * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](./api.html#query_Query-select).
  87. * @param {Boolean} [skipId=false] optional boolean. If true, mongoose doesn't add an `_id` field to the document.
  88. * @inherits Document http://mongoosejs.com/docs/api/document.html
  89. * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.
  90. * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.
  91. * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event.
  92. * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed.
  93. * @api public
  94. */
  95. function Model(doc, fields, skipId) {
  96. if (fields instanceof Schema) {
  97. throw new TypeError('2nd argument to `Model` must be a POJO or string, ' +
  98. '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' +
  99. '`mongoose.Model()`.');
  100. }
  101. Document.call(this, doc, fields, skipId);
  102. }
  103. /*!
  104. * Inherits from Document.
  105. *
  106. * All Model.prototype features are available on
  107. * top level (non-sub) documents.
  108. */
  109. Model.prototype.__proto__ = Document.prototype;
  110. Model.prototype.$isMongooseModelPrototype = true;
  111. /**
  112. * Connection the model uses.
  113. *
  114. * @api public
  115. * @property db
  116. * @memberOf Model
  117. * @instance
  118. */
  119. Model.prototype.db;
  120. /**
  121. * Collection the model uses.
  122. *
  123. * This property is read-only. Modifying this property is a no-op.
  124. *
  125. * @api public
  126. * @property collection
  127. * @memberOf Model
  128. * @instance
  129. */
  130. Model.prototype.collection;
  131. /**
  132. * Internal collection the model uses.
  133. *
  134. * This property is read-only. Modifying this property is a no-op.
  135. *
  136. * @api private
  137. * @property collection
  138. * @memberOf Model
  139. * @instance
  140. */
  141. Model.prototype.$__collection;
  142. /**
  143. * The name of the model
  144. *
  145. * @api public
  146. * @property modelName
  147. * @memberOf Model
  148. * @instance
  149. */
  150. Model.prototype.modelName;
  151. /**
  152. * Additional properties to attach to the query when calling `save()` and
  153. * `isNew` is false.
  154. *
  155. * @api public
  156. * @property $where
  157. * @memberOf Model
  158. * @instance
  159. */
  160. Model.prototype.$where;
  161. /**
  162. * If this is a discriminator model, `baseModelName` is the name of
  163. * the base model.
  164. *
  165. * @api public
  166. * @property baseModelName
  167. * @memberOf Model
  168. * @instance
  169. */
  170. Model.prototype.baseModelName;
  171. /**
  172. * Event emitter that reports any errors that occurred. Useful for global error
  173. * handling.
  174. *
  175. * ####Example:
  176. *
  177. * MyModel.events.on('error', err => console.log(err.message));
  178. *
  179. * // Prints a 'CastError' because of the above handler
  180. * await MyModel.findOne({ _id: 'notanid' }).catch(noop);
  181. *
  182. * @api public
  183. * @fires error whenever any query or model function errors
  184. * @memberOf Model
  185. * @static events
  186. */
  187. Model.events;
  188. /*!
  189. * Compiled middleware for this model. Set in `applyHooks()`.
  190. *
  191. * @api private
  192. * @property _middleware
  193. * @memberOf Model
  194. * @static
  195. */
  196. Model._middleware;
  197. /*!
  198. * ignore
  199. */
  200. function _applyCustomWhere(doc, where) {
  201. if (doc.$where == null) {
  202. return;
  203. }
  204. for (const key of Object.keys(doc.$where)) {
  205. where[key] = doc.$where[key];
  206. }
  207. }
  208. /*!
  209. * ignore
  210. */
  211. Model.prototype.$__handleSave = function(options, callback) {
  212. const _this = this;
  213. let saveOptions = {};
  214. applyWriteConcern(this.$__schema, options);
  215. if (typeof options.writeConcern != 'undefined') {
  216. saveOptions.writeConcern = {};
  217. if ('w' in options.writeConcern) {
  218. saveOptions.writeConcern.w = options.writeConcern.w;
  219. }
  220. if ('j' in options.writeConcern) {
  221. saveOptions.writeConcern.j = options.writeConcern.j;
  222. }
  223. if ('wtimeout' in options.writeConcern) {
  224. saveOptions.writeConcern.wtimeout = options.writeConcern.wtimeout;
  225. }
  226. } else {
  227. if ('w' in options) {
  228. saveOptions.w = options.w;
  229. }
  230. if ('j' in options) {
  231. saveOptions.j = options.j;
  232. }
  233. if ('wtimeout' in options) {
  234. saveOptions.wtimeout = options.wtimeout;
  235. }
  236. }
  237. if ('checkKeys' in options) {
  238. saveOptions.checkKeys = options.checkKeys;
  239. }
  240. const session = this.$session();
  241. if (!saveOptions.hasOwnProperty('session')) {
  242. saveOptions.session = session;
  243. }
  244. if (Object.keys(saveOptions).length === 0) {
  245. saveOptions = null;
  246. }
  247. if (this.$isNew) {
  248. // send entire doc
  249. const obj = this.toObject(saveToObjectOptions);
  250. if ((obj || {})._id === void 0) {
  251. // documents must have an _id else mongoose won't know
  252. // what to update later if more changes are made. the user
  253. // wouldn't know what _id was generated by mongodb either
  254. // nor would the ObjectId generated by mongodb necessarily
  255. // match the schema definition.
  256. immediate(function() {
  257. callback(new MongooseError('document must have an _id before saving'));
  258. });
  259. return;
  260. }
  261. this.$__version(true, obj);
  262. this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) {
  263. if (err) {
  264. _setIsNew(_this, true);
  265. callback(err, null);
  266. return;
  267. }
  268. callback(null, ret);
  269. });
  270. this.$__reset();
  271. _setIsNew(this, false);
  272. // Make it possible to retry the insert
  273. this.$__.inserting = true;
  274. } else {
  275. // Make sure we don't treat it as a new object on error,
  276. // since it already exists
  277. this.$__.inserting = false;
  278. const delta = this.$__delta();
  279. if (delta) {
  280. if (delta instanceof MongooseError) {
  281. callback(delta);
  282. return;
  283. }
  284. const where = this.$__where(delta[0]);
  285. if (where instanceof MongooseError) {
  286. callback(where);
  287. return;
  288. }
  289. _applyCustomWhere(this, where);
  290. this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, (err, ret) => {
  291. if (err) {
  292. this.$__undoReset();
  293. callback(err);
  294. return;
  295. }
  296. ret.$where = where;
  297. callback(null, ret);
  298. });
  299. } else {
  300. const optionsWithCustomValues = Object.assign({}, options, saveOptions);
  301. const where = this.$__where();
  302. if (this.$__schema.options.optimisticConcurrency) {
  303. const key = this.$__schema.options.versionKey;
  304. const val = this.$__getValue(key);
  305. if (val != null) {
  306. where[key] = val;
  307. }
  308. }
  309. this.constructor.exists(where, optionsWithCustomValues).
  310. then((documentExists) => {
  311. if (!documentExists) {
  312. const matchedCount = 0;
  313. return callback(null, { $where: where, matchedCount });
  314. }
  315. const matchedCount = 1;
  316. callback(null, { $where: where, matchedCount });
  317. }).
  318. catch(callback);
  319. return;
  320. }
  321. // store the modified paths before the document is reset
  322. this.$__.modifiedPaths = this.modifiedPaths();
  323. this.$__reset();
  324. _setIsNew(this, false);
  325. }
  326. };
  327. /*!
  328. * ignore
  329. */
  330. Model.prototype.$__save = function(options, callback) {
  331. this.$__handleSave(options, (error, result) => {
  332. const hooks = this.$__schema.s.hooks;
  333. if (error) {
  334. return hooks.execPost('save:error', this, [this], { error: error }, (error) => {
  335. callback(error, this);
  336. });
  337. }
  338. let numAffected = 0;
  339. const writeConcern = options != null ?
  340. options.writeConcern != null ?
  341. options.writeConcern.w :
  342. options.w :
  343. 0;
  344. if (writeConcern !== 0) {
  345. // Skip checking if write succeeded if writeConcern is set to
  346. // unacknowledged writes, because otherwise `numAffected` will always be 0
  347. if (result != null) {
  348. if (Array.isArray(result)) {
  349. numAffected = result.length;
  350. } else if (result.matchedCount != null) {
  351. numAffected = result.matchedCount;
  352. } else {
  353. numAffected = result;
  354. }
  355. }
  356. const versionBump = this.$__.version || this.$__schema.options.optimisticConcurrency;
  357. // was this an update that required a version bump?
  358. if (versionBump && !this.$__.inserting) {
  359. const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version);
  360. this.$__.version = undefined;
  361. const key = this.$__schema.options.versionKey;
  362. const version = this.$__getValue(key) || 0;
  363. if (numAffected <= 0) {
  364. // the update failed. pass an error back
  365. this.$__undoReset();
  366. const err = this.$__.$versionError ||
  367. new VersionError(this, version, this.$__.modifiedPaths);
  368. return callback(err);
  369. }
  370. // increment version if was successful
  371. if (doIncrement) {
  372. this.$__setValue(key, version + 1);
  373. }
  374. }
  375. if (result != null && numAffected <= 0) {
  376. this.$__undoReset();
  377. error = new DocumentNotFoundError(result.$where,
  378. this.constructor.modelName, numAffected, result);
  379. return hooks.execPost('save:error', this, [this], { error: error }, (error) => {
  380. callback(error, this);
  381. });
  382. }
  383. }
  384. this.$__.saving = undefined;
  385. this.$__.savedState = {};
  386. this.$emit('save', this, numAffected);
  387. this.constructor.emit('save', this, numAffected);
  388. callback(null, this);
  389. });
  390. };
  391. /*!
  392. * ignore
  393. */
  394. function generateVersionError(doc, modifiedPaths) {
  395. const key = doc.$__schema.options.versionKey;
  396. if (!key) {
  397. return null;
  398. }
  399. const version = doc.$__getValue(key) || 0;
  400. return new VersionError(doc, version, modifiedPaths);
  401. }
  402. /**
  403. * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`,
  404. * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation with just the modified paths if `isNew` is `false`.
  405. *
  406. * ####Example:
  407. *
  408. * product.sold = Date.now();
  409. * product = await product.save();
  410. *
  411. * If save is successful, the returned promise will fulfill with the document
  412. * saved.
  413. *
  414. * ####Example:
  415. *
  416. * const newProduct = await product.save();
  417. * newProduct === product; // true
  418. *
  419. * @param {Object} [options] options optional options
  420. * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session).
  421. * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead.
  422. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating.
  423. * @param {Boolean} [options.validateModifiedOnly=false] if `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths.
  424. * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern)
  425. * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern)
  426. * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern).
  427. * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names)
  428. * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`.
  429. * @param {Function} [fn] optional callback
  430. * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating).
  431. * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise.
  432. * @api public
  433. * @see middleware http://mongoosejs.com/docs/middleware.html
  434. */
  435. Model.prototype.save = function(options, fn) {
  436. let parallelSave;
  437. this.$op = 'save';
  438. if (this.$__.saving) {
  439. parallelSave = new ParallelSaveError(this);
  440. } else {
  441. this.$__.saving = new ParallelSaveError(this);
  442. }
  443. if (typeof options === 'function') {
  444. fn = options;
  445. options = undefined;
  446. }
  447. options = new SaveOptions(options);
  448. if (options.hasOwnProperty('session')) {
  449. this.$session(options.session);
  450. }
  451. this.$__.$versionError = generateVersionError(this, this.modifiedPaths());
  452. fn = this.constructor.$handleCallbackError(fn);
  453. return this.constructor.db.base._promiseOrCallback(fn, cb => {
  454. cb = this.constructor.$wrapCallback(cb);
  455. if (parallelSave) {
  456. this.$__handleReject(parallelSave);
  457. return cb(parallelSave);
  458. }
  459. this.$__.saveOptions = options;
  460. this.$__save(options, error => {
  461. this.$__.saving = undefined;
  462. delete this.$__.saveOptions;
  463. delete this.$__.$versionError;
  464. this.$op = null;
  465. if (error) {
  466. this.$__handleReject(error);
  467. return cb(error);
  468. }
  469. cb(null, this);
  470. });
  471. }, this.constructor.events);
  472. };
  473. Model.prototype.$save = Model.prototype.save;
  474. /*!
  475. * Determines whether versioning should be skipped for the given path
  476. *
  477. * @param {Document} self
  478. * @param {String} path
  479. * @return {Boolean} true if versioning should be skipped for the given path
  480. */
  481. function shouldSkipVersioning(self, path) {
  482. const skipVersioning = self.$__schema.options.skipVersioning;
  483. if (!skipVersioning) return false;
  484. // Remove any array indexes from the path
  485. path = path.replace(/\.\d+\./, '.');
  486. return skipVersioning[path];
  487. }
  488. /*!
  489. * Apply the operation to the delta (update) clause as
  490. * well as track versioning for our where clause.
  491. *
  492. * @param {Document} self
  493. * @param {Object} where
  494. * @param {Object} delta
  495. * @param {Object} data
  496. * @param {Mixed} val
  497. * @param {String} [operation]
  498. */
  499. function operand(self, where, delta, data, val, op) {
  500. // delta
  501. op || (op = '$set');
  502. if (!delta[op]) delta[op] = {};
  503. delta[op][data.path] = val;
  504. // disabled versioning?
  505. if (self.$__schema.options.versionKey === false) return;
  506. // path excluded from versioning?
  507. if (shouldSkipVersioning(self, data.path)) return;
  508. // already marked for versioning?
  509. if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return;
  510. if (self.$__schema.options.optimisticConcurrency) {
  511. self.$__.version = VERSION_ALL;
  512. return;
  513. }
  514. switch (op) {
  515. case '$set':
  516. case '$unset':
  517. case '$pop':
  518. case '$pull':
  519. case '$pullAll':
  520. case '$push':
  521. case '$addToSet':
  522. break;
  523. default:
  524. // nothing to do
  525. return;
  526. }
  527. // ensure updates sent with positional notation are
  528. // editing the correct array element.
  529. // only increment the version if an array position changes.
  530. // modifying elements of an array is ok if position does not change.
  531. if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') {
  532. if (/\.\d+\.|\.\d+$/.test(data.path)) {
  533. increment.call(self);
  534. } else {
  535. self.$__.version = VERSION_INC;
  536. }
  537. } else if (/^\$p/.test(op)) {
  538. // potentially changing array positions
  539. increment.call(self);
  540. } else if (Array.isArray(val)) {
  541. // $set an array
  542. increment.call(self);
  543. } else if (/\.\d+\.|\.\d+$/.test(data.path)) {
  544. // now handling $set, $unset
  545. // subpath of array
  546. self.$__.version = VERSION_WHERE;
  547. }
  548. }
  549. /*!
  550. * Compiles an update and where clause for a `val` with _atomics.
  551. *
  552. * @param {Document} self
  553. * @param {Object} where
  554. * @param {Object} delta
  555. * @param {Object} data
  556. * @param {Array} value
  557. */
  558. function handleAtomics(self, where, delta, data, value) {
  559. if (delta.$set && delta.$set[data.path]) {
  560. // $set has precedence over other atomics
  561. return;
  562. }
  563. if (typeof value.$__getAtomics === 'function') {
  564. value.$__getAtomics().forEach(function(atomic) {
  565. const op = atomic[0];
  566. const val = atomic[1];
  567. operand(self, where, delta, data, val, op);
  568. });
  569. return;
  570. }
  571. // legacy support for plugins
  572. const atomics = value[arrayAtomicsSymbol];
  573. const ops = Object.keys(atomics);
  574. let i = ops.length;
  575. let val;
  576. let op;
  577. if (i === 0) {
  578. // $set
  579. if (utils.isMongooseObject(value)) {
  580. value = value.toObject({ depopulate: 1, _isNested: true });
  581. } else if (value.valueOf) {
  582. value = value.valueOf();
  583. }
  584. return operand(self, where, delta, data, value);
  585. }
  586. function iter(mem) {
  587. return utils.isMongooseObject(mem)
  588. ? mem.toObject({ depopulate: 1, _isNested: true })
  589. : mem;
  590. }
  591. while (i--) {
  592. op = ops[i];
  593. val = atomics[op];
  594. if (utils.isMongooseObject(val)) {
  595. val = val.toObject({ depopulate: true, transform: false, _isNested: true });
  596. } else if (Array.isArray(val)) {
  597. val = val.map(iter);
  598. } else if (val.valueOf) {
  599. val = val.valueOf();
  600. }
  601. if (op === '$addToSet') {
  602. val = { $each: val };
  603. }
  604. operand(self, where, delta, data, val, op);
  605. }
  606. }
  607. /**
  608. * Produces a special query document of the modified properties used in updates.
  609. *
  610. * @api private
  611. * @method $__delta
  612. * @memberOf Model
  613. * @instance
  614. */
  615. Model.prototype.$__delta = function() {
  616. const dirty = this.$__dirty();
  617. if (!dirty.length && VERSION_ALL !== this.$__.version) {
  618. return;
  619. }
  620. const where = {};
  621. const delta = {};
  622. const len = dirty.length;
  623. const divergent = [];
  624. let d = 0;
  625. where._id = this._doc._id;
  626. // If `_id` is an object, need to depopulate, but also need to be careful
  627. // because `_id` can technically be null (see gh-6406)
  628. if (get(where, '_id.$__', null) != null) {
  629. where._id = where._id.toObject({ transform: false, depopulate: true });
  630. }
  631. for (; d < len; ++d) {
  632. const data = dirty[d];
  633. let value = data.value;
  634. const match = checkDivergentArray(this, data.path, value);
  635. if (match) {
  636. divergent.push(match);
  637. continue;
  638. }
  639. const pop = this.$populated(data.path, true);
  640. if (!pop && this.$__.selected) {
  641. // If any array was selected using an $elemMatch projection, we alter the path and where clause
  642. // NOTE: MongoDB only supports projected $elemMatch on top level array.
  643. const pathSplit = data.path.split('.');
  644. const top = pathSplit[0];
  645. if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) {
  646. // If the selected array entry was modified
  647. if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') {
  648. where[top] = this.$__.selected[top];
  649. pathSplit[1] = '$';
  650. data.path = pathSplit.join('.');
  651. }
  652. // if the selected array was modified in any other way throw an error
  653. else {
  654. divergent.push(data.path);
  655. continue;
  656. }
  657. }
  658. }
  659. if (divergent.length) continue;
  660. if (value === undefined) {
  661. operand(this, where, delta, data, 1, '$unset');
  662. } else if (value === null) {
  663. operand(this, where, delta, data, null);
  664. } else if (utils.isMongooseArray(value) && value.$path() && value[arrayAtomicsSymbol]) {
  665. // arrays and other custom types (support plugins etc)
  666. handleAtomics(this, where, delta, data, value);
  667. } else if (value[MongooseBuffer.pathSymbol] && Buffer.isBuffer(value)) {
  668. // MongooseBuffer
  669. value = value.toObject();
  670. operand(this, where, delta, data, value);
  671. } else {
  672. value = utils.clone(value, {
  673. depopulate: true,
  674. transform: false,
  675. virtuals: false,
  676. getters: false,
  677. _isNested: true
  678. });
  679. operand(this, where, delta, data, value);
  680. }
  681. }
  682. if (divergent.length) {
  683. return new DivergentArrayError(divergent);
  684. }
  685. if (this.$__.version) {
  686. this.$__version(where, delta);
  687. }
  688. return [where, delta];
  689. };
  690. /*!
  691. * Determine if array was populated with some form of filter and is now
  692. * being updated in a manner which could overwrite data unintentionally.
  693. *
  694. * @see https://github.com/Automattic/mongoose/issues/1334
  695. * @param {Document} doc
  696. * @param {String} path
  697. * @return {String|undefined}
  698. */
  699. function checkDivergentArray(doc, path, array) {
  700. // see if we populated this path
  701. const pop = doc.$populated(path, true);
  702. if (!pop && doc.$__.selected) {
  703. // If any array was selected using an $elemMatch projection, we deny the update.
  704. // NOTE: MongoDB only supports projected $elemMatch on top level array.
  705. const top = path.split('.')[0];
  706. if (doc.$__.selected[top + '.$']) {
  707. return top;
  708. }
  709. }
  710. if (!(pop && utils.isMongooseArray(array))) return;
  711. // If the array was populated using options that prevented all
  712. // documents from being returned (match, skip, limit) or they
  713. // deselected the _id field, $pop and $set of the array are
  714. // not safe operations. If _id was deselected, we do not know
  715. // how to remove elements. $pop will pop off the _id from the end
  716. // of the array in the db which is not guaranteed to be the
  717. // same as the last element we have here. $set of the entire array
  718. // would be similarly destructive as we never received all
  719. // elements of the array and potentially would overwrite data.
  720. const check = pop.options.match ||
  721. pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted
  722. pop.options.options && pop.options.options.skip || // 0 is permitted
  723. pop.options.select && // deselected _id?
  724. (pop.options.select._id === 0 ||
  725. /\s?-_id\s?/.test(pop.options.select));
  726. if (check) {
  727. const atomics = array[arrayAtomicsSymbol];
  728. if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) {
  729. return path;
  730. }
  731. }
  732. }
  733. /**
  734. * Appends versioning to the where and update clauses.
  735. *
  736. * @api private
  737. * @method $__version
  738. * @memberOf Model
  739. * @instance
  740. */
  741. Model.prototype.$__version = function(where, delta) {
  742. const key = this.$__schema.options.versionKey;
  743. if (where === true) {
  744. // this is an insert
  745. if (key) {
  746. setDottedPath(delta, key, 0);
  747. this.$__setValue(key, 0);
  748. }
  749. return;
  750. }
  751. if (key === false) {
  752. return;
  753. }
  754. // updates
  755. // only apply versioning if our versionKey was selected. else
  756. // there is no way to select the correct version. we could fail
  757. // fast here and force them to include the versionKey but
  758. // thats a bit intrusive. can we do this automatically?
  759. if (!this.$__isSelected(key)) {
  760. return;
  761. }
  762. // $push $addToSet don't need the where clause set
  763. if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {
  764. const value = this.$__getValue(key);
  765. if (value != null) where[key] = value;
  766. }
  767. if (VERSION_INC === (VERSION_INC & this.$__.version)) {
  768. if (get(delta.$set, key, null) != null) {
  769. // Version key is getting set, means we'll increment the doc's version
  770. // after a successful save, so we should set the incremented version so
  771. // future saves don't fail (gh-5779)
  772. ++delta.$set[key];
  773. } else {
  774. delta.$inc = delta.$inc || {};
  775. delta.$inc[key] = 1;
  776. }
  777. }
  778. };
  779. /**
  780. * Signal that we desire an increment of this documents version.
  781. *
  782. * ####Example:
  783. *
  784. * Model.findById(id, function (err, doc) {
  785. * doc.increment();
  786. * doc.save(function (err) { .. })
  787. * })
  788. *
  789. * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey
  790. * @api public
  791. */
  792. function increment() {
  793. this.$__.version = VERSION_ALL;
  794. return this;
  795. }
  796. Model.prototype.increment = increment;
  797. /**
  798. * Returns a query object
  799. *
  800. * @api private
  801. * @method $__where
  802. * @memberOf Model
  803. * @instance
  804. */
  805. Model.prototype.$__where = function _where(where) {
  806. where || (where = {});
  807. if (!where._id) {
  808. where._id = this._doc._id;
  809. }
  810. if (this._doc._id === void 0) {
  811. return new MongooseError('No _id found on document!');
  812. }
  813. return where;
  814. };
  815. /**
  816. * Removes this document from the db.
  817. *
  818. * ####Example:
  819. * product.remove(function (err, product) {
  820. * if (err) return handleError(err);
  821. * Product.findById(product._id, function (err, product) {
  822. * console.log(product) // null
  823. * })
  824. * })
  825. *
  826. *
  827. * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to receive errors
  828. *
  829. * ####Example:
  830. * product.remove().then(function (product) {
  831. * ...
  832. * }).catch(function (err) {
  833. * assert.ok(err)
  834. * })
  835. *
  836. * @param {Object} [options]
  837. * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session).
  838. * @param {function(err,product)} [fn] optional callback
  839. * @return {Promise} Promise
  840. * @api public
  841. */
  842. Model.prototype.remove = function remove(options, fn) {
  843. if (typeof options === 'function') {
  844. fn = options;
  845. options = undefined;
  846. }
  847. options = new RemoveOptions(options);
  848. if (options.hasOwnProperty('session')) {
  849. this.$session(options.session);
  850. }
  851. this.$op = 'remove';
  852. fn = this.constructor.$handleCallbackError(fn);
  853. return this.constructor.db.base._promiseOrCallback(fn, cb => {
  854. cb = this.constructor.$wrapCallback(cb);
  855. this.$__remove(options, (err, res) => {
  856. this.$op = null;
  857. cb(err, res);
  858. });
  859. }, this.constructor.events);
  860. };
  861. /*!
  862. * Alias for remove
  863. */
  864. Model.prototype.$remove = Model.prototype.remove;
  865. Model.prototype.delete = Model.prototype.remove;
  866. /**
  867. * Removes this document from the db. Equivalent to `.remove()`.
  868. *
  869. * ####Example:
  870. * product = await product.deleteOne();
  871. * await Product.findById(product._id); // null
  872. *
  873. * @param {function(err,product)} [fn] optional callback
  874. * @return {Promise} Promise
  875. * @api public
  876. */
  877. Model.prototype.deleteOne = function deleteOne(options, fn) {
  878. if (typeof options === 'function') {
  879. fn = options;
  880. options = undefined;
  881. }
  882. if (!options) {
  883. options = {};
  884. }
  885. fn = this.constructor.$handleCallbackError(fn);
  886. return this.constructor.db.base._promiseOrCallback(fn, cb => {
  887. cb = this.constructor.$wrapCallback(cb);
  888. this.$__deleteOne(options, cb);
  889. }, this.constructor.events);
  890. };
  891. /*!
  892. * ignore
  893. */
  894. Model.prototype.$__remove = function $__remove(options, cb) {
  895. if (this.$__.isDeleted) {
  896. return immediate(() => cb(null, this));
  897. }
  898. const where = this.$__where();
  899. if (where instanceof MongooseError) {
  900. return cb(where);
  901. }
  902. _applyCustomWhere(this, where);
  903. const session = this.$session();
  904. if (!options.hasOwnProperty('session')) {
  905. options.session = session;
  906. }
  907. this[modelCollectionSymbol].deleteOne(where, options, err => {
  908. if (!err) {
  909. this.$__.isDeleted = true;
  910. this.$emit('remove', this);
  911. this.constructor.emit('remove', this);
  912. return cb(null, this);
  913. }
  914. this.$__.isDeleted = false;
  915. cb(err);
  916. });
  917. };
  918. /*!
  919. * ignore
  920. */
  921. Model.prototype.$__deleteOne = Model.prototype.$__remove;
  922. /**
  923. * Returns another Model instance.
  924. *
  925. * ####Example:
  926. *
  927. * const doc = new Tank;
  928. * doc.model('User').findById(id, callback);
  929. *
  930. * @param {String} name model name
  931. * @api public
  932. */
  933. Model.prototype.model = function model(name) {
  934. return this[modelDbSymbol].model(name);
  935. };
  936. /**
  937. * Returns a document with `_id` only if at least one document exists in the database that matches
  938. * the given `filter`, and `null` otherwise.
  939. *
  940. * Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to
  941. * `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()`
  942. *
  943. * ####Example:
  944. * await Character.deleteMany({});
  945. * await Character.create({ name: 'Jean-Luc Picard' });
  946. *
  947. * await Character.exists({ name: /picard/i }); // { _id: ... }
  948. * await Character.exists({ name: /riker/i }); // null
  949. *
  950. * This function triggers the following middleware.
  951. *
  952. * - `findOne()`
  953. *
  954. * @param {Object} filter
  955. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  956. * @param {Function} [callback] callback
  957. * @return {Query}
  958. */
  959. Model.exists = function exists(filter, options, callback) {
  960. _checkContext(this, 'exists');
  961. if (typeof options === 'function') {
  962. callback = options;
  963. options = null;
  964. }
  965. const query = this.findOne(filter).
  966. select({ _id: 1 }).
  967. lean().
  968. setOptions(options);
  969. if (typeof callback === 'function') {
  970. return query.exec(callback);
  971. }
  972. return query;
  973. };
  974. /**
  975. * Adds a discriminator type.
  976. *
  977. * ####Example:
  978. *
  979. * function BaseSchema() {
  980. * Schema.apply(this, arguments);
  981. *
  982. * this.add({
  983. * name: String,
  984. * createdAt: Date
  985. * });
  986. * }
  987. * util.inherits(BaseSchema, Schema);
  988. *
  989. * const PersonSchema = new BaseSchema();
  990. * const BossSchema = new BaseSchema({ department: String });
  991. *
  992. * const Person = mongoose.model('Person', PersonSchema);
  993. * const Boss = Person.discriminator('Boss', BossSchema);
  994. * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`
  995. *
  996. * const employeeSchema = new Schema({ boss: ObjectId });
  997. * const Employee = Person.discriminator('Employee', employeeSchema, 'staff');
  998. * new Employee().__t; // "staff" because of 3rd argument above
  999. *
  1000. * @param {String} name discriminator model name
  1001. * @param {Schema} schema discriminator model schema
  1002. * @param {Object|String} [options] If string, same as `options.value`.
  1003. * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
  1004. * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
  1005. * @param {Boolean} [options.overwriteModels=false] by default, Mongoose does not allow you to define a discriminator with the same name as another discriminator. Set this to allow overwriting discriminators with the same name.
  1006. * @return {Model} The newly created discriminator model
  1007. * @api public
  1008. */
  1009. Model.discriminator = function(name, schema, options) {
  1010. let model;
  1011. if (typeof name === 'function') {
  1012. model = name;
  1013. name = utils.getFunctionName(model);
  1014. if (!(model.prototype instanceof Model)) {
  1015. throw new MongooseError('The provided class ' + name + ' must extend Model');
  1016. }
  1017. }
  1018. options = options || {};
  1019. const value = utils.isPOJO(options) ? options.value : options;
  1020. const clone = get(options, 'clone', true);
  1021. _checkContext(this, 'discriminator');
  1022. if (utils.isObject(schema) && !schema.instanceOfSchema) {
  1023. schema = new Schema(schema);
  1024. }
  1025. if (schema instanceof Schema && clone) {
  1026. schema = schema.clone();
  1027. }
  1028. schema = discriminator(this, name, schema, value, true);
  1029. if (this.db.models[name] && !schema.options.overwriteModels) {
  1030. throw new OverwriteModelError(name);
  1031. }
  1032. schema.$isRootDiscriminator = true;
  1033. schema.$globalPluginsApplied = true;
  1034. model = this.db.model(model || name, schema, this.$__collection.name);
  1035. this.discriminators[name] = model;
  1036. const d = this.discriminators[name];
  1037. d.prototype.__proto__ = this.prototype;
  1038. Object.defineProperty(d, 'baseModelName', {
  1039. value: this.modelName,
  1040. configurable: true,
  1041. writable: false
  1042. });
  1043. // apply methods and statics
  1044. applyMethods(d, schema);
  1045. applyStatics(d, schema);
  1046. if (this[subclassedSymbol] != null) {
  1047. for (const submodel of this[subclassedSymbol]) {
  1048. submodel.discriminators = submodel.discriminators || {};
  1049. submodel.discriminators[name] =
  1050. model.__subclass(model.db, schema, submodel.collection.name);
  1051. }
  1052. }
  1053. return d;
  1054. };
  1055. /*!
  1056. * Make sure `this` is a model
  1057. */
  1058. function _checkContext(ctx, fnName) {
  1059. // Check context, because it is easy to mistakenly type
  1060. // `new Model.discriminator()` and get an incomprehensible error
  1061. if (ctx == null || ctx === global) {
  1062. throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' +
  1063. 'model as `this`. Make sure you are calling `MyModel.' + fnName + '()` ' +
  1064. 'where `MyModel` is a Mongoose model.');
  1065. } else if (ctx[modelSymbol] == null) {
  1066. throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' +
  1067. 'model as `this`. Make sure you are not calling ' +
  1068. '`new Model.' + fnName + '()`');
  1069. }
  1070. }
  1071. // Model (class) features
  1072. /*!
  1073. * Give the constructor the ability to emit events.
  1074. */
  1075. for (const i in EventEmitter.prototype) {
  1076. Model[i] = EventEmitter.prototype[i];
  1077. }
  1078. /**
  1079. * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/),
  1080. * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
  1081. *
  1082. * Mongoose calls this function automatically when a model is created using
  1083. * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or
  1084. * [`connection.model()`](/docs/api.html#connection_Connection-model), so you
  1085. * don't need to call it. This function is also idempotent, so you may call it
  1086. * to get back a promise that will resolve when your indexes are finished
  1087. * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes)
  1088. *
  1089. * ####Example:
  1090. *
  1091. * const eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  1092. * // This calls `Event.init()` implicitly, so you don't need to call
  1093. * // `Event.init()` on your own.
  1094. * const Event = mongoose.model('Event', eventSchema);
  1095. *
  1096. * Event.init().then(function(Event) {
  1097. * // You can also use `Event.on('index')` if you prefer event emitters
  1098. * // over promises.
  1099. * console.log('Indexes are done building!');
  1100. * });
  1101. *
  1102. * @api public
  1103. * @param {Function} [callback]
  1104. * @returns {Promise}
  1105. */
  1106. Model.init = function init(callback) {
  1107. _checkContext(this, 'init');
  1108. this.schema.emit('init', this);
  1109. if (this.$init != null) {
  1110. if (callback) {
  1111. this.$init.then(() => callback(), err => callback(err));
  1112. return null;
  1113. }
  1114. return this.$init;
  1115. }
  1116. const Promise = PromiseProvider.get();
  1117. const autoIndex = utils.getOption('autoIndex',
  1118. this.schema.options, this.db.config, this.db.base.options);
  1119. const autoCreate = utils.getOption('autoCreate',
  1120. this.schema.options, this.db.config, this.db.base.options);
  1121. const _ensureIndexes = autoIndex ?
  1122. cb => this.ensureIndexes({ _automatic: true }, cb) :
  1123. cb => cb();
  1124. const _createCollection = autoCreate ?
  1125. cb => this.createCollection({}, cb) :
  1126. cb => cb();
  1127. this.$init = new Promise((resolve, reject) => {
  1128. _createCollection(error => {
  1129. if (error) {
  1130. return reject(error);
  1131. }
  1132. _ensureIndexes(error => {
  1133. if (error) {
  1134. return reject(error);
  1135. }
  1136. resolve(this);
  1137. });
  1138. });
  1139. });
  1140. if (callback) {
  1141. this.$init.then(() => callback(), err => callback(err));
  1142. this.$caught = true;
  1143. return null;
  1144. } else {
  1145. const _catch = this.$init.catch;
  1146. const _this = this;
  1147. this.$init.catch = function() {
  1148. this.$caught = true;
  1149. return _catch.apply(_this.$init, arguments);
  1150. };
  1151. }
  1152. return this.$init;
  1153. };
  1154. /**
  1155. * Create the collection for this model. By default, if no indexes are specified,
  1156. * mongoose will not create the collection for the model until any documents are
  1157. * created. Use this method to create the collection explicitly.
  1158. *
  1159. * Note 1: You may need to call this before starting a transaction
  1160. * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations
  1161. *
  1162. * Note 2: You don't have to call this if your schema contains index or unique field.
  1163. * In that case, just use `Model.init()`
  1164. *
  1165. * ####Example:
  1166. *
  1167. * const userSchema = new Schema({ name: String })
  1168. * const User = mongoose.model('User', userSchema);
  1169. *
  1170. * User.createCollection().then(function(collection) {
  1171. * console.log('Collection is created!');
  1172. * });
  1173. *
  1174. * @api public
  1175. * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection)
  1176. * @param {Function} [callback]
  1177. * @returns {Promise}
  1178. */
  1179. Model.createCollection = function createCollection(options, callback) {
  1180. _checkContext(this, 'createCollection');
  1181. if (typeof options === 'string') {
  1182. throw new MongooseError('You can\'t specify a new collection name in Model.createCollection.' +
  1183. 'This is not like Connection.createCollection. Only options are accepted here.');
  1184. } else if (typeof options === 'function') {
  1185. callback = options;
  1186. options = void 0;
  1187. }
  1188. const schemaCollation = get(this, ['schema', 'options', 'collation'], null);
  1189. if (schemaCollation != null) {
  1190. options = Object.assign({ collation: schemaCollation }, options);
  1191. }
  1192. const capped = get(this, ['schema', 'options', 'capped']);
  1193. if (capped) {
  1194. options = Object.assign({ capped: true }, capped, options);
  1195. }
  1196. const timeseries = get(this, ['schema', 'options', 'timeseries']);
  1197. if (timeseries != null) {
  1198. options = Object.assign({ timeseries }, options);
  1199. }
  1200. callback = this.$handleCallbackError(callback);
  1201. return this.db.base._promiseOrCallback(callback, cb => {
  1202. cb = this.$wrapCallback(cb);
  1203. this.db.createCollection(this.$__collection.collectionName, options, utils.tick((err) => {
  1204. if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) {
  1205. return cb(err);
  1206. }
  1207. this.$__collection = this.db.collection(this.$__collection.collectionName, options);
  1208. cb(null, this.$__collection);
  1209. }));
  1210. }, this.events);
  1211. };
  1212. /**
  1213. * Makes the indexes in MongoDB match the indexes defined in this model's
  1214. * schema. This function will drop any indexes that are not defined in
  1215. * the model's schema except the `_id` index, and build any indexes that
  1216. * are in your schema but not in MongoDB.
  1217. *
  1218. * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes)
  1219. * for more information.
  1220. *
  1221. * ####Example:
  1222. *
  1223. * const schema = new Schema({ name: { type: String, unique: true } });
  1224. * const Customer = mongoose.model('Customer', schema);
  1225. * await Customer.collection.createIndex({ age: 1 }); // Index is not in schema
  1226. * // Will drop the 'age' index and create an index on `name`
  1227. * await Customer.syncIndexes();
  1228. *
  1229. * @param {Object} [options] options to pass to `ensureIndexes()`
  1230. * @param {Boolean} [options.background=null] if specified, overrides each index's `background` property
  1231. * @param {Function} [callback] optional callback
  1232. * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback.
  1233. * @api public
  1234. */
  1235. Model.syncIndexes = function syncIndexes(options, callback) {
  1236. _checkContext(this, 'syncIndexes');
  1237. callback = this.$handleCallbackError(callback);
  1238. return this.db.base._promiseOrCallback(callback, cb => {
  1239. cb = this.$wrapCallback(cb);
  1240. this.createCollection(err => {
  1241. if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) {
  1242. return cb(err);
  1243. }
  1244. this.cleanIndexes((err, dropped) => {
  1245. if (err != null) {
  1246. return cb(err);
  1247. }
  1248. this.createIndexes(options, err => {
  1249. if (err != null) {
  1250. return cb(err);
  1251. }
  1252. cb(null, dropped);
  1253. });
  1254. });
  1255. });
  1256. }, this.events);
  1257. };
  1258. /**
  1259. * Does a dry-run of Model.syncIndexes(), meaning that
  1260. * the result of this function would be the result of
  1261. * Model.syncIndexes().
  1262. *
  1263. * @param {Object} options not used at all.
  1264. * @param {Function} callback optional callback
  1265. * @returns {Promise} which containts an object, {toDrop, toCreate}, which
  1266. * are indexes that would be dropped in mongodb and indexes that would be created in mongodb.
  1267. */
  1268. Model.diffIndexes = function diffIndexes(options, callback) {
  1269. const toDrop = [];
  1270. const toCreate = [];
  1271. callback = this.$handleCallbackError(callback);
  1272. return this.db.base._promiseOrCallback(callback, cb => {
  1273. cb = this.$wrapCallback(cb);
  1274. this.listIndexes((err, indexes) => {
  1275. if (indexes === undefined) {
  1276. indexes = [];
  1277. }
  1278. const schemaIndexes = this.schema.indexes();
  1279. // Iterate through the indexes created in mongodb and
  1280. // compare against the indexes in the schema.
  1281. for (const index of indexes) {
  1282. let found = false;
  1283. // Never try to drop `_id` index, MongoDB server doesn't allow it
  1284. if (isDefaultIdIndex(index)) {
  1285. continue;
  1286. }
  1287. for (const schemaIndex of schemaIndexes) {
  1288. const key = schemaIndex[0];
  1289. const options = _decorateDiscriminatorIndexOptions(this,
  1290. utils.clone(schemaIndex[1]));
  1291. if (isIndexEqual(key, options, index)) {
  1292. found = true;
  1293. }
  1294. }
  1295. if (!found) {
  1296. toDrop.push(index.name);
  1297. }
  1298. }
  1299. // Iterate through the indexes created on the schema and
  1300. // compare against the indexes in mongodb.
  1301. for (const schemaIndex of schemaIndexes) {
  1302. const key = schemaIndex[0];
  1303. let found = false;
  1304. const options = _decorateDiscriminatorIndexOptions(this,
  1305. utils.clone(schemaIndex[1]));
  1306. for (const index of indexes) {
  1307. if (isDefaultIdIndex(index)) {
  1308. continue;
  1309. }
  1310. if (isIndexEqual(key, options, index)) {
  1311. found = true;
  1312. }
  1313. }
  1314. if (!found) {
  1315. toCreate.push(key);
  1316. }
  1317. }
  1318. cb(null, { toDrop, toCreate });
  1319. });
  1320. });
  1321. };
  1322. /**
  1323. * Deletes all indexes that aren't defined in this model's schema. Used by
  1324. * `syncIndexes()`.
  1325. *
  1326. * The returned promise resolves to a list of the dropped indexes' names as an array
  1327. *
  1328. * @param {Function} [callback] optional callback
  1329. * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback.
  1330. * @api public
  1331. */
  1332. Model.cleanIndexes = function cleanIndexes(callback) {
  1333. _checkContext(this, 'cleanIndexes');
  1334. callback = this.$handleCallbackError(callback);
  1335. return this.db.base._promiseOrCallback(callback, cb => {
  1336. const collection = this.$__collection;
  1337. this.listIndexes((err, indexes) => {
  1338. if (err != null) {
  1339. return cb(err);
  1340. }
  1341. const schemaIndexes = this.schema.indexes();
  1342. const toDrop = [];
  1343. for (const index of indexes) {
  1344. let found = false;
  1345. // Never try to drop `_id` index, MongoDB server doesn't allow it
  1346. if (isDefaultIdIndex(index)) {
  1347. continue;
  1348. }
  1349. for (const schemaIndex of schemaIndexes) {
  1350. const key = schemaIndex[0];
  1351. const options = _decorateDiscriminatorIndexOptions(this,
  1352. utils.clone(schemaIndex[1]));
  1353. if (isIndexEqual(key, options, index)) {
  1354. found = true;
  1355. }
  1356. }
  1357. if (!found) {
  1358. toDrop.push(index.name);
  1359. }
  1360. }
  1361. if (toDrop.length === 0) {
  1362. return cb(null, []);
  1363. }
  1364. dropIndexes(toDrop, cb);
  1365. });
  1366. function dropIndexes(toDrop, cb) {
  1367. let remaining = toDrop.length;
  1368. let error = false;
  1369. toDrop.forEach(indexName => {
  1370. collection.dropIndex(indexName, err => {
  1371. if (err != null) {
  1372. error = true;
  1373. return cb(err);
  1374. }
  1375. if (!error) {
  1376. --remaining || cb(null, toDrop);
  1377. }
  1378. });
  1379. });
  1380. }
  1381. });
  1382. };
  1383. /**
  1384. * Lists the indexes currently defined in MongoDB. This may or may not be
  1385. * the same as the indexes defined in your schema depending on whether you
  1386. * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you
  1387. * build indexes manually.
  1388. *
  1389. * @param {Function} [cb] optional callback
  1390. * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback.
  1391. * @api public
  1392. */
  1393. Model.listIndexes = function init(callback) {
  1394. _checkContext(this, 'listIndexes');
  1395. const _listIndexes = cb => {
  1396. this.$__collection.listIndexes().toArray(cb);
  1397. };
  1398. callback = this.$handleCallbackError(callback);
  1399. return this.db.base._promiseOrCallback(callback, cb => {
  1400. cb = this.$wrapCallback(cb);
  1401. // Buffering
  1402. if (this.$__collection.buffer) {
  1403. this.$__collection.addQueue(_listIndexes, [cb]);
  1404. } else {
  1405. _listIndexes(cb);
  1406. }
  1407. }, this.events);
  1408. };
  1409. /**
  1410. * Sends `createIndex` commands to mongo for each index declared in the schema.
  1411. * The `createIndex` commands are sent in series.
  1412. *
  1413. * ####Example:
  1414. *
  1415. * Event.ensureIndexes(function (err) {
  1416. * if (err) return handleError(err);
  1417. * });
  1418. *
  1419. * After completion, an `index` event is emitted on this `Model` passing an error if one occurred.
  1420. *
  1421. * ####Example:
  1422. *
  1423. * const eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  1424. * const Event = mongoose.model('Event', eventSchema);
  1425. *
  1426. * Event.on('index', function (err) {
  1427. * if (err) console.error(err); // error occurred during index creation
  1428. * })
  1429. *
  1430. * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._
  1431. *
  1432. * @param {Object} [options] internal options
  1433. * @param {Function} [cb] optional callback
  1434. * @return {Promise}
  1435. * @api public
  1436. */
  1437. Model.ensureIndexes = function ensureIndexes(options, callback) {
  1438. _checkContext(this, 'ensureIndexes');
  1439. if (typeof options === 'function') {
  1440. callback = options;
  1441. options = null;
  1442. }
  1443. callback = this.$handleCallbackError(callback);
  1444. return this.db.base._promiseOrCallback(callback, cb => {
  1445. cb = this.$wrapCallback(cb);
  1446. _ensureIndexes(this, options || {}, error => {
  1447. if (error) {
  1448. return cb(error);
  1449. }
  1450. cb(null);
  1451. });
  1452. }, this.events);
  1453. };
  1454. /**
  1455. * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
  1456. * function.
  1457. *
  1458. * @param {Object} [options] internal options
  1459. * @param {Function} [cb] optional callback
  1460. * @return {Promise}
  1461. * @api public
  1462. */
  1463. Model.createIndexes = function createIndexes(options, callback) {
  1464. _checkContext(this, 'createIndexes');
  1465. if (typeof options === 'function') {
  1466. callback = options;
  1467. options = {};
  1468. }
  1469. options = options || {};
  1470. options.createIndex = true;
  1471. return this.ensureIndexes(options, callback);
  1472. };
  1473. /*!
  1474. * ignore
  1475. */
  1476. function _ensureIndexes(model, options, callback) {
  1477. const indexes = model.schema.indexes();
  1478. let indexError;
  1479. options = options || {};
  1480. const done = function(err) {
  1481. if (err && !model.$caught) {
  1482. model.emit('error', err);
  1483. }
  1484. model.emit('index', err || indexError);
  1485. callback && callback(err || indexError);
  1486. };
  1487. for (const index of indexes) {
  1488. if (isDefaultIdIndex(index)) {
  1489. utils.warn('mongoose: Cannot specify a custom index on `_id` for ' +
  1490. 'model name "' + model.modelName + '", ' +
  1491. 'MongoDB does not allow overwriting the default `_id` index. See ' +
  1492. 'http://bit.ly/mongodb-id-index');
  1493. }
  1494. }
  1495. if (!indexes.length) {
  1496. immediate(function() {
  1497. done();
  1498. });
  1499. return;
  1500. }
  1501. // Indexes are created one-by-one to support how MongoDB < 2.4 deals
  1502. // with background indexes.
  1503. const indexSingleDone = function(err, fields, options, name) {
  1504. model.emit('index-single-done', err, fields, options, name);
  1505. };
  1506. const indexSingleStart = function(fields, options) {
  1507. model.emit('index-single-start', fields, options);
  1508. };
  1509. const baseSchema = model.schema._baseSchema;
  1510. const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : [];
  1511. const create = function() {
  1512. if (options._automatic) {
  1513. if (model.schema.options.autoIndex === false ||
  1514. (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) {
  1515. return done();
  1516. }
  1517. }
  1518. const index = indexes.shift();
  1519. if (!index) {
  1520. return done();
  1521. }
  1522. if (options._automatic && index[1]._autoIndex === false) {
  1523. return create();
  1524. }
  1525. if (baseSchemaIndexes.find(i => utils.deepEqual(i, index))) {
  1526. return create();
  1527. }
  1528. const indexFields = utils.clone(index[0]);
  1529. const indexOptions = utils.clone(index[1]);
  1530. let isTextIndex = false;
  1531. for (const key of Object.keys(indexFields)) {
  1532. if (indexFields[key] === 'text') {
  1533. isTextIndex = true;
  1534. }
  1535. }
  1536. delete indexOptions._autoIndex;
  1537. _decorateDiscriminatorIndexOptions(model, indexOptions);
  1538. applyWriteConcern(model.schema, indexOptions);
  1539. indexSingleStart(indexFields, options);
  1540. if ('background' in options) {
  1541. indexOptions.background = options.background;
  1542. }
  1543. if (model.schema.options.hasOwnProperty('collation') &&
  1544. !indexOptions.hasOwnProperty('collation') &&
  1545. !isTextIndex) {
  1546. indexOptions.collation = model.schema.options.collation;
  1547. }
  1548. model.collection.createIndex(indexFields, indexOptions, utils.tick(function(err, name) {
  1549. indexSingleDone(err, indexFields, indexOptions, name);
  1550. if (err) {
  1551. if (!indexError) {
  1552. indexError = err;
  1553. }
  1554. if (!model.$caught) {
  1555. model.emit('error', err);
  1556. }
  1557. }
  1558. create();
  1559. }));
  1560. };
  1561. immediate(function() {
  1562. // If buffering is off, do this manually.
  1563. if (options._automatic && !model.collection.collection) {
  1564. model.collection.addQueue(create, []);
  1565. } else {
  1566. create();
  1567. }
  1568. });
  1569. }
  1570. function _decorateDiscriminatorIndexOptions(model, indexOptions) {
  1571. // If the model is a discriminator and it has a unique index, add a
  1572. // partialFilterExpression by default so the unique index will only apply
  1573. // to that discriminator.
  1574. if (model.baseModelName != null &&
  1575. !('partialFilterExpression' in indexOptions) &&
  1576. !('sparse' in indexOptions)) {
  1577. const value = (
  1578. model.schema.discriminatorMapping &&
  1579. model.schema.discriminatorMapping.value
  1580. ) || model.modelName;
  1581. const discriminatorKey = model.schema.options.discriminatorKey;
  1582. indexOptions.partialFilterExpression = { [discriminatorKey]: value };
  1583. }
  1584. return indexOptions;
  1585. }
  1586. /**
  1587. * Schema the model uses.
  1588. *
  1589. * @property schema
  1590. * @receiver Model
  1591. * @api public
  1592. * @memberOf Model
  1593. */
  1594. Model.schema;
  1595. /*!
  1596. * Connection instance the model uses.
  1597. *
  1598. * @property db
  1599. * @api public
  1600. * @memberOf Model
  1601. */
  1602. Model.db;
  1603. /*!
  1604. * Collection the model uses.
  1605. *
  1606. * @property collection
  1607. * @api public
  1608. * @memberOf Model
  1609. */
  1610. Model.collection;
  1611. /**
  1612. * Internal collection the model uses.
  1613. *
  1614. * @property collection
  1615. * @api private
  1616. * @memberOf Model
  1617. */
  1618. Model.$__collection;
  1619. /**
  1620. * Base Mongoose instance the model uses.
  1621. *
  1622. * @property base
  1623. * @api public
  1624. * @memberOf Model
  1625. */
  1626. Model.base;
  1627. /**
  1628. * Registered discriminators for this model.
  1629. *
  1630. * @property discriminators
  1631. * @api public
  1632. * @memberOf Model
  1633. */
  1634. Model.discriminators;
  1635. /**
  1636. * Translate any aliases fields/conditions so the final query or document object is pure
  1637. *
  1638. * ####Example:
  1639. *
  1640. * Character
  1641. * .find(Character.translateAliases({
  1642. * '名': 'Eddard Stark' // Alias for 'name'
  1643. * })
  1644. * .exec(function(err, characters) {})
  1645. *
  1646. * ####Note:
  1647. * Only translate arguments of object type anything else is returned raw
  1648. *
  1649. * @param {Object} raw fields/conditions that may contain aliased keys
  1650. * @return {Object} the translated 'pure' fields/conditions
  1651. */
  1652. Model.translateAliases = function translateAliases(fields) {
  1653. _checkContext(this, 'translateAliases');
  1654. const translate = (key, value) => {
  1655. let alias;
  1656. const translated = [];
  1657. const fieldKeys = key.split('.');
  1658. let currentSchema = this.schema;
  1659. for (const i in fieldKeys) {
  1660. const name = fieldKeys[i];
  1661. if (currentSchema && currentSchema.aliases[name]) {
  1662. alias = currentSchema.aliases[name];
  1663. // Alias found,
  1664. translated.push(alias);
  1665. } else {
  1666. alias = name;
  1667. // Alias not found, so treat as un-aliased key
  1668. translated.push(name);
  1669. }
  1670. // Check if aliased path is a schema
  1671. if (currentSchema && currentSchema.paths[alias]) {
  1672. currentSchema = currentSchema.paths[alias].schema;
  1673. }
  1674. else
  1675. currentSchema = null;
  1676. }
  1677. const translatedKey = translated.join('.');
  1678. if (fields instanceof Map)
  1679. fields.set(translatedKey, value);
  1680. else
  1681. fields[translatedKey] = value;
  1682. if (translatedKey !== key) {
  1683. // We'll be using the translated key instead
  1684. if (fields instanceof Map) {
  1685. // Delete from map
  1686. fields.delete(key);
  1687. } else {
  1688. // Delete from object
  1689. delete fields[key]; // We'll be using the translated key instead
  1690. }
  1691. }
  1692. return fields;
  1693. };
  1694. if (typeof fields === 'object') {
  1695. // Fields is an object (query conditions or document fields)
  1696. if (fields instanceof Map) {
  1697. // A Map was supplied
  1698. for (const field of new Map(fields)) {
  1699. fields = translate(field[0], field[1]);
  1700. }
  1701. } else {
  1702. // Infer a regular object was supplied
  1703. for (const key of Object.keys(fields)) {
  1704. fields = translate(key, fields[key]);
  1705. if (key[0] === '$') {
  1706. if (Array.isArray(fields[key])) {
  1707. for (const i in fields[key]) {
  1708. // Recursively translate nested queries
  1709. fields[key][i] = this.translateAliases(fields[key][i]);
  1710. }
  1711. }
  1712. }
  1713. }
  1714. }
  1715. return fields;
  1716. } else {
  1717. // Don't know typeof fields
  1718. return fields;
  1719. }
  1720. };
  1721. /**
  1722. * Removes all documents that match `conditions` from the collection.
  1723. * To remove just the first document that matches `conditions`, set the `single`
  1724. * option to true.
  1725. *
  1726. * This method is deprecated. See [Deprecation Warnings](../deprecations.html#remove) for details.
  1727. *
  1728. * ####Example:
  1729. *
  1730. * const res = await Character.remove({ name: 'Eddard Stark' });
  1731. * res.deletedCount; // Number of documents removed
  1732. *
  1733. * ####Note:
  1734. *
  1735. * This method sends a remove command directly to MongoDB, no Mongoose documents
  1736. * are involved. Because no Mongoose documents are involved, Mongoose does
  1737. * not execute [document middleware](/docs/middleware.html#types-of-middleware).
  1738. *
  1739. * @deprecated
  1740. * @param {Object} conditions
  1741. * @param {Object} [options]
  1742. * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation.
  1743. * @param {Function} [callback]
  1744. * @return {Query}
  1745. * @api public
  1746. */
  1747. Model.remove = function remove(conditions, options, callback) {
  1748. _checkContext(this, 'remove');
  1749. if (typeof conditions === 'function') {
  1750. callback = conditions;
  1751. conditions = {};
  1752. options = null;
  1753. } else if (typeof options === 'function') {
  1754. callback = options;
  1755. options = null;
  1756. }
  1757. // get the mongodb collection object
  1758. const mq = new this.Query({}, {}, this, this.$__collection);
  1759. mq.setOptions(options);
  1760. callback = this.$handleCallbackError(callback);
  1761. return mq.remove(conditions, callback);
  1762. };
  1763. /**
  1764. * Deletes the first document that matches `conditions` from the collection.
  1765. * It returns an object with the property `deletedCount` indicating how many documents were deleted.
  1766. * Behaves like `remove()`, but deletes at most one document regardless of the
  1767. * `single` option.
  1768. *
  1769. * ####Example:
  1770. *
  1771. * await Character.deleteOne({ name: 'Eddard Stark' }); // returns {deletedCount: 1}
  1772. *
  1773. * ####Note:
  1774. *
  1775. * This function triggers `deleteOne` query hooks. Read the
  1776. * [middleware docs](/docs/middleware.html#naming) to learn more.
  1777. *
  1778. * @param {Object} conditions
  1779. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1780. * @param {Function} [callback]
  1781. * @return {Query}
  1782. * @api public
  1783. */
  1784. Model.deleteOne = function deleteOne(conditions, options, callback) {
  1785. _checkContext(this, 'deleteOne');
  1786. if (typeof conditions === 'function') {
  1787. callback = conditions;
  1788. conditions = {};
  1789. options = null;
  1790. }
  1791. else if (typeof options === 'function') {
  1792. callback = options;
  1793. options = null;
  1794. }
  1795. const mq = new this.Query({}, {}, this, this.$__collection);
  1796. mq.setOptions(options);
  1797. callback = this.$handleCallbackError(callback);
  1798. return mq.deleteOne(conditions, callback);
  1799. };
  1800. /**
  1801. * Deletes all of the documents that match `conditions` from the collection.
  1802. * It returns an object with the property `deletedCount` containing the number of documents deleted.
  1803. * Behaves like `remove()`, but deletes all documents that match `conditions`
  1804. * regardless of the `single` option.
  1805. *
  1806. * ####Example:
  1807. *
  1808. * await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); // returns {deletedCount: x} where x is the number of documents deleted.
  1809. *
  1810. * ####Note:
  1811. *
  1812. * This function triggers `deleteMany` query hooks. Read the
  1813. * [middleware docs](/docs/middleware.html#naming) to learn more.
  1814. *
  1815. * @param {Object} conditions
  1816. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1817. * @param {Function} [callback]
  1818. * @return {Query}
  1819. * @api public
  1820. */
  1821. Model.deleteMany = function deleteMany(conditions, options, callback) {
  1822. _checkContext(this, 'deleteMany');
  1823. if (typeof conditions === 'function') {
  1824. callback = conditions;
  1825. conditions = {};
  1826. options = null;
  1827. } else if (typeof options === 'function') {
  1828. callback = options;
  1829. options = null;
  1830. }
  1831. const mq = new this.Query({}, {}, this, this.$__collection);
  1832. mq.setOptions(options);
  1833. callback = this.$handleCallbackError(callback);
  1834. return mq.deleteMany(conditions, callback);
  1835. };
  1836. /**
  1837. * Finds documents.
  1838. *
  1839. * Mongoose casts the `filter` to match the model's schema before the command is sent.
  1840. * See our [query casting tutorial](/docs/tutorials/query_casting.html) for
  1841. * more information on how Mongoose casts `filter`.
  1842. *
  1843. * ####Examples:
  1844. *
  1845. * // find all documents
  1846. * await MyModel.find({});
  1847. *
  1848. * // find all documents named john and at least 18
  1849. * await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();
  1850. *
  1851. * // executes, passing results to callback
  1852. * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
  1853. *
  1854. * // executes, name LIKE john and only selecting the "name" and "friends" fields
  1855. * await MyModel.find({ name: /john/i }, 'name friends').exec();
  1856. *
  1857. * // passing options
  1858. * await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();
  1859. *
  1860. * @param {Object|ObjectId} filter
  1861. * @param {Object|String|Array<String>} [projection] optional fields to return, see [`Query.prototype.select()`](http://mongoosejs.com/docs/api.html#query_Query-select)
  1862. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1863. * @param {Function} [callback]
  1864. * @return {Query}
  1865. * @see field selection #query_Query-select
  1866. * @see query casting /docs/tutorials/query_casting.html
  1867. * @api public
  1868. */
  1869. Model.find = function find(conditions, projection, options, callback) {
  1870. _checkContext(this, 'find');
  1871. if (typeof conditions === 'function') {
  1872. callback = conditions;
  1873. conditions = {};
  1874. projection = null;
  1875. options = null;
  1876. } else if (typeof projection === 'function') {
  1877. callback = projection;
  1878. projection = null;
  1879. options = null;
  1880. } else if (typeof options === 'function') {
  1881. callback = options;
  1882. options = null;
  1883. }
  1884. const mq = new this.Query({}, {}, this, this.$__collection);
  1885. mq.select(projection);
  1886. mq.setOptions(options);
  1887. if (this.schema.discriminatorMapping &&
  1888. this.schema.discriminatorMapping.isRoot &&
  1889. mq.selectedInclusively()) {
  1890. // Need to select discriminator key because original schema doesn't have it
  1891. mq.select(this.schema.options.discriminatorKey);
  1892. }
  1893. callback = this.$handleCallbackError(callback);
  1894. return mq.find(conditions, callback);
  1895. };
  1896. /**
  1897. * Finds a single document by its _id field. `findById(id)` is almost*
  1898. * equivalent to `findOne({ _id: id })`. If you want to query by a document's
  1899. * `_id`, use `findById()` instead of `findOne()`.
  1900. *
  1901. * The `id` is cast based on the Schema before sending the command.
  1902. *
  1903. * This function triggers the following middleware.
  1904. *
  1905. * - `findOne()`
  1906. *
  1907. * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see
  1908. * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent
  1909. * to `findOne({})` and return arbitrary documents. However, mongoose
  1910. * translates `findById(undefined)` into `findOne({ _id: null })`.
  1911. *
  1912. * ####Example:
  1913. *
  1914. * // Find the adventure with the given `id`, or `null` if not found
  1915. * await Adventure.findById(id).exec();
  1916. *
  1917. * // using callback
  1918. * Adventure.findById(id, function (err, adventure) {});
  1919. *
  1920. * // select only the adventures name and length
  1921. * await Adventure.findById(id, 'name length').exec();
  1922. *
  1923. * @param {Any} id value of `_id` to query by
  1924. * @param {Object|String|Array<String>} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  1925. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1926. * @param {Function} [callback]
  1927. * @return {Query}
  1928. * @see field selection #query_Query-select
  1929. * @see lean queries /docs/tutorials/lean.html
  1930. * @see findById in Mongoose https://masteringjs.io/tutorials/mongoose/find-by-id
  1931. * @api public
  1932. */
  1933. Model.findById = function findById(id, projection, options, callback) {
  1934. _checkContext(this, 'findById');
  1935. if (typeof id === 'undefined') {
  1936. id = null;
  1937. }
  1938. callback = this.$handleCallbackError(callback);
  1939. return this.findOne({ _id: id }, projection, options, callback);
  1940. };
  1941. /**
  1942. * Finds one document.
  1943. *
  1944. * The `conditions` are cast to their respective SchemaTypes before the command is sent.
  1945. *
  1946. * *Note:* `conditions` is optional, and if `conditions` is null or undefined,
  1947. * mongoose will send an empty `findOne` command to MongoDB, which will return
  1948. * an arbitrary document. If you're querying by `_id`, use `findById()` instead.
  1949. *
  1950. * ####Example:
  1951. *
  1952. * // Find one adventure whose `country` is 'Croatia', otherwise `null`
  1953. * await Adventure.findOne({ country: 'Croatia' }).exec();
  1954. *
  1955. * // using callback
  1956. * Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});
  1957. *
  1958. * // select only the adventures name and length
  1959. * await Adventure.findOne({ country: 'Croatia' }, 'name length').exec();
  1960. *
  1961. * @param {Object} [conditions]
  1962. * @param {Object|String|Array<String>} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  1963. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  1964. * @param {Function} [callback]
  1965. * @return {Query}
  1966. * @see field selection #query_Query-select
  1967. * @see lean queries /docs/tutorials/lean.html
  1968. * @api public
  1969. */
  1970. Model.findOne = function findOne(conditions, projection, options, callback) {
  1971. _checkContext(this, 'findOne');
  1972. if (typeof options === 'function') {
  1973. callback = options;
  1974. options = null;
  1975. } else if (typeof projection === 'function') {
  1976. callback = projection;
  1977. projection = null;
  1978. options = null;
  1979. } else if (typeof conditions === 'function') {
  1980. callback = conditions;
  1981. conditions = {};
  1982. projection = null;
  1983. options = null;
  1984. }
  1985. const mq = new this.Query({}, {}, this, this.$__collection);
  1986. mq.select(projection);
  1987. mq.setOptions(options);
  1988. if (this.schema.discriminatorMapping &&
  1989. this.schema.discriminatorMapping.isRoot &&
  1990. mq.selectedInclusively()) {
  1991. mq.select(this.schema.options.discriminatorKey);
  1992. }
  1993. callback = this.$handleCallbackError(callback);
  1994. return mq.findOne(conditions, callback);
  1995. };
  1996. /**
  1997. * Estimates the number of documents in the MongoDB collection. Faster than
  1998. * using `countDocuments()` for large collections because
  1999. * `estimatedDocumentCount()` uses collection metadata rather than scanning
  2000. * the entire collection.
  2001. *
  2002. * ####Example:
  2003. *
  2004. * const numAdventures = await Adventure.estimatedDocumentCount();
  2005. *
  2006. * @param {Object} [options]
  2007. * @param {Function} [callback]
  2008. * @return {Query}
  2009. * @api public
  2010. */
  2011. Model.estimatedDocumentCount = function estimatedDocumentCount(options, callback) {
  2012. _checkContext(this, 'estimatedDocumentCount');
  2013. const mq = new this.Query({}, {}, this, this.$__collection);
  2014. callback = this.$handleCallbackError(callback);
  2015. return mq.estimatedDocumentCount(options, callback);
  2016. };
  2017. /**
  2018. * Counts number of documents matching `filter` in a database collection.
  2019. *
  2020. * ####Example:
  2021. *
  2022. * Adventure.countDocuments({ type: 'jungle' }, function (err, count) {
  2023. * console.log('there are %d jungle adventures', count);
  2024. * });
  2025. *
  2026. * If you want to count all documents in a large collection,
  2027. * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount)
  2028. * instead. If you call `countDocuments({})`, MongoDB will always execute
  2029. * a full collection scan and **not** use any indexes.
  2030. *
  2031. * The `countDocuments()` function is similar to `count()`, but there are a
  2032. * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments).
  2033. * Below are the operators that `count()` supports but `countDocuments()` does not,
  2034. * and the suggested replacement:
  2035. *
  2036. * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/)
  2037. * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center)
  2038. * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere)
  2039. *
  2040. * @param {Object} filter
  2041. * @param {Function} [callback]
  2042. * @return {Query}
  2043. * @api public
  2044. */
  2045. Model.countDocuments = function countDocuments(conditions, options, callback) {
  2046. _checkContext(this, 'countDocuments');
  2047. if (typeof conditions === 'function') {
  2048. callback = conditions;
  2049. conditions = {};
  2050. }
  2051. if (typeof options === 'function') {
  2052. callback = options;
  2053. options = null;
  2054. }
  2055. const mq = new this.Query({}, {}, this, this.$__collection);
  2056. if (options != null) {
  2057. mq.setOptions(options);
  2058. }
  2059. callback = this.$handleCallbackError(callback);
  2060. return mq.countDocuments(conditions, callback);
  2061. };
  2062. /**
  2063. * Counts number of documents that match `filter` in a database collection.
  2064. *
  2065. * This method is deprecated. If you want to count the number of documents in
  2066. * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount)
  2067. * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead.
  2068. *
  2069. * ####Example:
  2070. *
  2071. * const count = await Adventure.count({ type: 'jungle' });
  2072. * console.log('there are %d jungle adventures', count);
  2073. *
  2074. * @deprecated
  2075. * @param {Object} filter
  2076. * @param {Function} [callback]
  2077. * @return {Query}
  2078. * @api public
  2079. */
  2080. Model.count = function count(conditions, callback) {
  2081. _checkContext(this, 'count');
  2082. if (typeof conditions === 'function') {
  2083. callback = conditions;
  2084. conditions = {};
  2085. }
  2086. const mq = new this.Query({}, {}, this, this.$__collection);
  2087. callback = this.$handleCallbackError(callback);
  2088. return mq.count(conditions, callback);
  2089. };
  2090. /**
  2091. * Creates a Query for a `distinct` operation.
  2092. *
  2093. * Passing a `callback` executes the query.
  2094. *
  2095. * ####Example
  2096. *
  2097. * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
  2098. * if (err) return handleError(err);
  2099. *
  2100. * assert(Array.isArray(result));
  2101. * console.log('unique urls with more than 100 clicks', result);
  2102. * })
  2103. *
  2104. * const query = Link.distinct('url');
  2105. * query.exec(callback);
  2106. *
  2107. * @param {String} field
  2108. * @param {Object} [conditions] optional
  2109. * @param {Function} [callback]
  2110. * @return {Query}
  2111. * @api public
  2112. */
  2113. Model.distinct = function distinct(field, conditions, callback) {
  2114. _checkContext(this, 'distinct');
  2115. const mq = new this.Query({}, {}, this, this.$__collection);
  2116. if (typeof conditions === 'function') {
  2117. callback = conditions;
  2118. conditions = {};
  2119. }
  2120. callback = this.$handleCallbackError(callback);
  2121. return mq.distinct(field, conditions, callback);
  2122. };
  2123. /**
  2124. * Creates a Query, applies the passed conditions, and returns the Query.
  2125. *
  2126. * For example, instead of writing:
  2127. *
  2128. * User.find({age: {$gte: 21, $lte: 65}}, callback);
  2129. *
  2130. * we can instead write:
  2131. *
  2132. * User.where('age').gte(21).lte(65).exec(callback);
  2133. *
  2134. * Since the Query class also supports `where` you can continue chaining
  2135. *
  2136. * User
  2137. * .where('age').gte(21).lte(65)
  2138. * .where('name', /^b/i)
  2139. * ... etc
  2140. *
  2141. * @param {String} path
  2142. * @param {Object} [val] optional value
  2143. * @return {Query}
  2144. * @api public
  2145. */
  2146. Model.where = function where(path, val) {
  2147. _checkContext(this, 'where');
  2148. void val; // eslint
  2149. const mq = new this.Query({}, {}, this, this.$__collection).find({});
  2150. return mq.where.apply(mq, arguments);
  2151. };
  2152. /**
  2153. * Creates a `Query` and specifies a `$where` condition.
  2154. *
  2155. * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.
  2156. *
  2157. * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});
  2158. *
  2159. * @param {String|Function} argument is a javascript string or anonymous function
  2160. * @method $where
  2161. * @memberOf Model
  2162. * @return {Query}
  2163. * @see Query.$where #query_Query-%24where
  2164. * @api public
  2165. */
  2166. Model.$where = function $where() {
  2167. _checkContext(this, '$where');
  2168. const mq = new this.Query({}, {}, this, this.$__collection).find({});
  2169. return mq.$where.apply(mq, arguments);
  2170. };
  2171. /**
  2172. * Issues a mongodb findAndModify update command.
  2173. *
  2174. * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned.
  2175. *
  2176. * ####Options:
  2177. *
  2178. * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  2179. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  2180. * - `overwrite`: bool - if true, replace the entire document.
  2181. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
  2182. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2183. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2184. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  2185. * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created.
  2186. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2187. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2188. *
  2189. * ####Examples:
  2190. *
  2191. * A.findOneAndUpdate(conditions, update, options, callback) // executes
  2192. * A.findOneAndUpdate(conditions, update, options) // returns Query
  2193. * A.findOneAndUpdate(conditions, update, callback) // executes
  2194. * A.findOneAndUpdate(conditions, update) // returns Query
  2195. * A.findOneAndUpdate() // returns Query
  2196. *
  2197. * ####Note:
  2198. *
  2199. * All top level update keys which are not `atomic` operation names are treated as set operations:
  2200. *
  2201. * ####Example:
  2202. *
  2203. * const query = { name: 'borne' };
  2204. * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)
  2205. *
  2206. * // is sent as
  2207. * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)
  2208. *
  2209. * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`.
  2210. *
  2211. * ####Note:
  2212. *
  2213. * `findOneAndX` and `findByIdAndX` functions support limited validation that
  2214. * you can enable by setting the `runValidators` option.
  2215. *
  2216. * If you need full-fledged validation, use the traditional approach of first
  2217. * retrieving the document.
  2218. *
  2219. * const doc = await Model.findById(id);
  2220. * doc.name = 'jason bourne';
  2221. * await doc.save();
  2222. *
  2223. * @param {Object} [conditions]
  2224. * @param {Object} [update]
  2225. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2226. * @param {String} [options.returnDocument='before'] Has two possible values, `'before'` and `'after'`. By default, it will return the document before the update was applied.
  2227. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html).
  2228. * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
  2229. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2230. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
  2231. * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace(conditions, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace).
  2232. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  2233. * @param {Object|String|Array<String>} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  2234. * @param {Function} [callback]
  2235. * @return {Query}
  2236. * @see Tutorial /docs/tutorials/findoneandupdate.html
  2237. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2238. * @api public
  2239. */
  2240. Model.findOneAndUpdate = function(conditions, update, options, callback) {
  2241. _checkContext(this, 'findOneAndUpdate');
  2242. if (typeof options === 'function') {
  2243. callback = options;
  2244. options = null;
  2245. } else if (arguments.length === 1) {
  2246. if (typeof conditions === 'function') {
  2247. const msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n'
  2248. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n'
  2249. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n'
  2250. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n'
  2251. + ' ' + this.modelName + '.findOneAndUpdate(update)\n'
  2252. + ' ' + this.modelName + '.findOneAndUpdate()\n';
  2253. throw new TypeError(msg);
  2254. }
  2255. update = conditions;
  2256. conditions = undefined;
  2257. }
  2258. callback = this.$handleCallbackError(callback);
  2259. let fields;
  2260. if (options) {
  2261. fields = options.fields || options.projection;
  2262. }
  2263. update = utils.clone(update, {
  2264. depopulate: true,
  2265. _isNested: true
  2266. });
  2267. _decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey);
  2268. const mq = new this.Query({}, {}, this, this.$__collection);
  2269. mq.select(fields);
  2270. return mq.findOneAndUpdate(conditions, update, options, callback);
  2271. };
  2272. /*!
  2273. * Decorate the update with a version key, if necessary
  2274. */
  2275. function _decorateUpdateWithVersionKey(update, options, versionKey) {
  2276. if (!versionKey || !get(options, 'upsert', false)) {
  2277. return;
  2278. }
  2279. const updatedPaths = modifiedPaths(update);
  2280. if (!updatedPaths[versionKey]) {
  2281. if (options.overwrite) {
  2282. update[versionKey] = 0;
  2283. } else {
  2284. if (!update.$setOnInsert) {
  2285. update.$setOnInsert = {};
  2286. }
  2287. update.$setOnInsert[versionKey] = 0;
  2288. }
  2289. }
  2290. }
  2291. /**
  2292. * Issues a mongodb findAndModify update command by a document's _id field.
  2293. * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`.
  2294. *
  2295. * Finds a matching document, updates it according to the `update` arg,
  2296. * passing any `options`, and returns the found document (if any) to the
  2297. * callback. The query executes if `callback` is passed.
  2298. *
  2299. * This function triggers the following middleware.
  2300. *
  2301. * - `findOneAndUpdate()`
  2302. *
  2303. * ####Options:
  2304. *
  2305. * - `new`: bool - true to return the modified document rather than the original. defaults to false
  2306. * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
  2307. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  2308. * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created.
  2309. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2310. * - `select`: sets the document fields to return
  2311. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2312. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2313. *
  2314. * ####Examples:
  2315. *
  2316. * A.findByIdAndUpdate(id, update, options, callback) // executes
  2317. * A.findByIdAndUpdate(id, update, options) // returns Query
  2318. * A.findByIdAndUpdate(id, update, callback) // executes
  2319. * A.findByIdAndUpdate(id, update) // returns Query
  2320. * A.findByIdAndUpdate() // returns Query
  2321. *
  2322. * ####Note:
  2323. *
  2324. * All top level update keys which are not `atomic` operation names are treated as set operations:
  2325. *
  2326. * ####Example:
  2327. *
  2328. * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)
  2329. *
  2330. * // is sent as
  2331. * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback)
  2332. *
  2333. * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`.
  2334. *
  2335. * ####Note:
  2336. *
  2337. * `findOneAndX` and `findByIdAndX` functions support limited validation. You can
  2338. * enable validation by setting the `runValidators` option.
  2339. *
  2340. * If you need full-fledged validation, use the traditional approach of first
  2341. * retrieving the document.
  2342. *
  2343. * Model.findById(id, function (err, doc) {
  2344. * if (err) ..
  2345. * doc.name = 'jason bourne';
  2346. * doc.save(callback);
  2347. * });
  2348. *
  2349. * @param {Object|Number|String} id value of `_id` to query by
  2350. * @param {Object} [update]
  2351. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2352. * @param {String} [options.returnDocument='before'] Has two possible values, `'before'` and `'after'`. By default, it will return the document before the update was applied.
  2353. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html).
  2354. * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
  2355. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2356. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
  2357. * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace({ _id: id }, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace).
  2358. * @param {Function} [callback]
  2359. * @return {Query}
  2360. * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate
  2361. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2362. * @api public
  2363. */
  2364. Model.findByIdAndUpdate = function(id, update, options, callback) {
  2365. _checkContext(this, 'findByIdAndUpdate');
  2366. callback = this.$handleCallbackError(callback);
  2367. if (arguments.length === 1) {
  2368. if (typeof id === 'function') {
  2369. const msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n'
  2370. + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n'
  2371. + ' ' + this.modelName + '.findByIdAndUpdate(id)\n'
  2372. + ' ' + this.modelName + '.findByIdAndUpdate()\n';
  2373. throw new TypeError(msg);
  2374. }
  2375. return this.findOneAndUpdate({ _id: id }, undefined);
  2376. }
  2377. // if a model is passed in instead of an id
  2378. if (id instanceof Document) {
  2379. id = id._id;
  2380. }
  2381. return this.findOneAndUpdate.call(this, { _id: id }, update, options, callback);
  2382. };
  2383. /**
  2384. * Issue a MongoDB `findOneAndDelete()` command.
  2385. *
  2386. * Finds a matching document, removes it, and passes the found document
  2387. * (if any) to the callback.
  2388. *
  2389. * Executes the query if `callback` is passed.
  2390. *
  2391. * This function triggers the following middleware.
  2392. *
  2393. * - `findOneAndDelete()`
  2394. *
  2395. * This function differs slightly from `Model.findOneAndRemove()` in that
  2396. * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/),
  2397. * as opposed to a `findOneAndDelete()` command. For most mongoose use cases,
  2398. * this distinction is purely pedantic. You should use `findOneAndDelete()`
  2399. * unless you have a good reason not to.
  2400. *
  2401. * ####Options:
  2402. *
  2403. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2404. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2405. * - `select`: sets the document fields to return, ex. `{ projection: { _id: 0 } }`
  2406. * - `projection`: equivalent to `select`
  2407. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2408. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2409. *
  2410. * ####Examples:
  2411. *
  2412. * A.findOneAndDelete(conditions, options, callback) // executes
  2413. * A.findOneAndDelete(conditions, options) // return Query
  2414. * A.findOneAndDelete(conditions, callback) // executes
  2415. * A.findOneAndDelete(conditions) // returns Query
  2416. * A.findOneAndDelete() // returns Query
  2417. *
  2418. * `findOneAndX` and `findByIdAndX` functions support limited validation. You can
  2419. * enable validation by setting the `runValidators` option.
  2420. *
  2421. * If you need full-fledged validation, use the traditional approach of first
  2422. * retrieving the document.
  2423. *
  2424. * Model.findById(id, function (err, doc) {
  2425. * if (err) ..
  2426. * doc.name = 'jason bourne';
  2427. * doc.save(callback);
  2428. * });
  2429. *
  2430. * @param {Object} conditions
  2431. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2432. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2433. * @param {Object|String|Array<String>} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  2434. * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
  2435. * @param {Function} [callback]
  2436. * @return {Query}
  2437. * @api public
  2438. */
  2439. Model.findOneAndDelete = function(conditions, options, callback) {
  2440. _checkContext(this, 'findOneAndDelete');
  2441. if (arguments.length === 1 && typeof conditions === 'function') {
  2442. const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n'
  2443. + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n'
  2444. + ' ' + this.modelName + '.findOneAndDelete(conditions)\n'
  2445. + ' ' + this.modelName + '.findOneAndDelete()\n';
  2446. throw new TypeError(msg);
  2447. }
  2448. if (typeof options === 'function') {
  2449. callback = options;
  2450. options = undefined;
  2451. }
  2452. callback = this.$handleCallbackError(callback);
  2453. let fields;
  2454. if (options) {
  2455. fields = options.select;
  2456. options.select = undefined;
  2457. }
  2458. const mq = new this.Query({}, {}, this, this.$__collection);
  2459. mq.select(fields);
  2460. return mq.findOneAndDelete(conditions, options, callback);
  2461. };
  2462. /**
  2463. * Issue a MongoDB `findOneAndDelete()` command by a document's _id field.
  2464. * In other words, `findByIdAndDelete(id)` is a shorthand for
  2465. * `findOneAndDelete({ _id: id })`.
  2466. *
  2467. * This function triggers the following middleware.
  2468. *
  2469. * - `findOneAndDelete()`
  2470. *
  2471. * @param {Object|Number|String} id value of `_id` to query by
  2472. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2473. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2474. * @param {Function} [callback]
  2475. * @return {Query}
  2476. * @see Model.findOneAndRemove #model_Model.findOneAndRemove
  2477. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2478. */
  2479. Model.findByIdAndDelete = function(id, options, callback) {
  2480. _checkContext(this, 'findByIdAndDelete');
  2481. if (arguments.length === 1 && typeof id === 'function') {
  2482. const msg = 'Model.findByIdAndDelete(): First argument must not be a function.\n\n'
  2483. + ' ' + this.modelName + '.findByIdAndDelete(id, callback)\n'
  2484. + ' ' + this.modelName + '.findByIdAndDelete(id)\n'
  2485. + ' ' + this.modelName + '.findByIdAndDelete()\n';
  2486. throw new TypeError(msg);
  2487. }
  2488. callback = this.$handleCallbackError(callback);
  2489. return this.findOneAndDelete({ _id: id }, options, callback);
  2490. };
  2491. /**
  2492. * Issue a MongoDB `findOneAndReplace()` command.
  2493. *
  2494. * Finds a matching document, replaces it with the provided doc, and passes the
  2495. * returned doc to the callback.
  2496. *
  2497. * Executes the query if `callback` is passed.
  2498. *
  2499. * This function triggers the following query middleware.
  2500. *
  2501. * - `findOneAndReplace()`
  2502. *
  2503. * ####Options:
  2504. *
  2505. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2506. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2507. * - `select`: sets the document fields to return
  2508. * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
  2509. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2510. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2511. *
  2512. * ####Examples:
  2513. *
  2514. * A.findOneAndReplace(conditions, options, callback) // executes
  2515. * A.findOneAndReplace(conditions, options) // return Query
  2516. * A.findOneAndReplace(conditions, callback) // executes
  2517. * A.findOneAndReplace(conditions) // returns Query
  2518. * A.findOneAndReplace() // returns Query
  2519. *
  2520. * @param {Object} filter Replace the first document that matches this filter
  2521. * @param {Object} [replacement] Replace with this document
  2522. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2523. * @param {String} [options.returnDocument='before'] Has two possible values, `'before'` and `'after'`. By default, it will return the document before the update was applied.
  2524. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html).
  2525. * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
  2526. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2527. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
  2528. * @param {Object|String|Array<String>} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  2529. * @param {Function} [callback]
  2530. * @return {Query}
  2531. * @api public
  2532. */
  2533. Model.findOneAndReplace = function(filter, replacement, options, callback) {
  2534. _checkContext(this, 'findOneAndReplace');
  2535. if (arguments.length === 1 && typeof filter === 'function') {
  2536. const msg = 'Model.findOneAndReplace(): First argument must not be a function.\n\n'
  2537. + ' ' + this.modelName + '.findOneAndReplace(conditions, callback)\n'
  2538. + ' ' + this.modelName + '.findOneAndReplace(conditions)\n'
  2539. + ' ' + this.modelName + '.findOneAndReplace()\n';
  2540. throw new TypeError(msg);
  2541. }
  2542. if (arguments.length === 3 && typeof options === 'function') {
  2543. callback = options;
  2544. options = replacement;
  2545. replacement = void 0;
  2546. }
  2547. if (arguments.length === 2 && typeof replacement === 'function') {
  2548. callback = replacement;
  2549. replacement = void 0;
  2550. options = void 0;
  2551. }
  2552. callback = this.$handleCallbackError(callback);
  2553. let fields;
  2554. if (options) {
  2555. fields = options.select;
  2556. options.select = undefined;
  2557. }
  2558. const mq = new this.Query({}, {}, this, this.$__collection);
  2559. mq.select(fields);
  2560. return mq.findOneAndReplace(filter, replacement, options, callback);
  2561. };
  2562. /**
  2563. * Issue a mongodb findAndModify remove command.
  2564. *
  2565. * Finds a matching document, removes it, passing the found document (if any) to the callback.
  2566. *
  2567. * Executes the query if `callback` is passed.
  2568. *
  2569. * This function triggers the following middleware.
  2570. *
  2571. * - `findOneAndRemove()`
  2572. *
  2573. * ####Options:
  2574. *
  2575. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2576. * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
  2577. * - `select`: sets the document fields to return
  2578. * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }`
  2579. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2580. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2581. *
  2582. * ####Examples:
  2583. *
  2584. * A.findOneAndRemove(conditions, options, callback) // executes
  2585. * A.findOneAndRemove(conditions, options) // return Query
  2586. * A.findOneAndRemove(conditions, callback) // executes
  2587. * A.findOneAndRemove(conditions) // returns Query
  2588. * A.findOneAndRemove() // returns Query
  2589. *
  2590. * `findOneAndX` and `findByIdAndX` functions support limited validation. You can
  2591. * enable validation by setting the `runValidators` option.
  2592. *
  2593. * If you need full-fledged validation, use the traditional approach of first
  2594. * retrieving the document.
  2595. *
  2596. * Model.findById(id, function (err, doc) {
  2597. * if (err) ..
  2598. * doc.name = 'jason bourne';
  2599. * doc.save(callback);
  2600. * });
  2601. *
  2602. * @param {Object} conditions
  2603. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2604. * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
  2605. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2606. * @param {Object|String|Array<String>} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  2607. * @param {Function} [callback]
  2608. * @return {Query}
  2609. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2610. * @api public
  2611. */
  2612. Model.findOneAndRemove = function(conditions, options, callback) {
  2613. _checkContext(this, 'findOneAndRemove');
  2614. if (arguments.length === 1 && typeof conditions === 'function') {
  2615. const msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n'
  2616. + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n'
  2617. + ' ' + this.modelName + '.findOneAndRemove(conditions)\n'
  2618. + ' ' + this.modelName + '.findOneAndRemove()\n';
  2619. throw new TypeError(msg);
  2620. }
  2621. if (typeof options === 'function') {
  2622. callback = options;
  2623. options = undefined;
  2624. }
  2625. callback = this.$handleCallbackError(callback);
  2626. let fields;
  2627. if (options) {
  2628. fields = options.select;
  2629. options.select = undefined;
  2630. }
  2631. const mq = new this.Query({}, {}, this, this.$__collection);
  2632. mq.select(fields);
  2633. return mq.findOneAndRemove(conditions, options, callback);
  2634. };
  2635. /**
  2636. * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`.
  2637. *
  2638. * Finds a matching document, removes it, passing the found document (if any) to the callback.
  2639. *
  2640. * Executes the query if `callback` is passed.
  2641. *
  2642. * This function triggers the following middleware.
  2643. *
  2644. * - `findOneAndRemove()`
  2645. *
  2646. * ####Options:
  2647. *
  2648. * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  2649. * - `select`: sets the document fields to return
  2650. * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
  2651. * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update
  2652. *
  2653. * ####Examples:
  2654. *
  2655. * A.findByIdAndRemove(id, options, callback) // executes
  2656. * A.findByIdAndRemove(id, options) // return Query
  2657. * A.findByIdAndRemove(id, callback) // executes
  2658. * A.findByIdAndRemove(id) // returns Query
  2659. * A.findByIdAndRemove() // returns Query
  2660. *
  2661. * @param {Object|Number|String} id value of `_id` to query by
  2662. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  2663. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  2664. * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html).
  2665. * @param {Object|String|Array<String>} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](#query_Query-select)
  2666. * @param {Function} [callback]
  2667. * @return {Query}
  2668. * @see Model.findOneAndRemove #model_Model.findOneAndRemove
  2669. * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command
  2670. */
  2671. Model.findByIdAndRemove = function(id, options, callback) {
  2672. _checkContext(this, 'findByIdAndRemove');
  2673. if (arguments.length === 1 && typeof id === 'function') {
  2674. const msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n'
  2675. + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n'
  2676. + ' ' + this.modelName + '.findByIdAndRemove(id)\n'
  2677. + ' ' + this.modelName + '.findByIdAndRemove()\n';
  2678. throw new TypeError(msg);
  2679. }
  2680. callback = this.$handleCallbackError(callback);
  2681. return this.findOneAndRemove({ _id: id }, options, callback);
  2682. };
  2683. /**
  2684. * Shortcut for saving one or more documents to the database.
  2685. * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in
  2686. * docs.
  2687. *
  2688. * This function triggers the following middleware.
  2689. *
  2690. * - `save()`
  2691. *
  2692. * ####Example:
  2693. *
  2694. * // Insert one new `Character` document
  2695. * await Character.create({ name: 'Jean-Luc Picard' });
  2696. *
  2697. * // Insert multiple new `Character` documents
  2698. * await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]);
  2699. *
  2700. * // Create a new character within a transaction. Note that you **must**
  2701. * // pass an array as the first parameter to `create()` if you want to
  2702. * // specify options.
  2703. * await Character.create([{ name: 'Jean-Luc Picard' }], { session });
  2704. *
  2705. * @param {Array|Object} docs Documents to insert, as a spread or array
  2706. * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread.
  2707. * @param {Function} [callback] callback
  2708. * @return {Promise}
  2709. * @api public
  2710. */
  2711. Model.create = function create(doc, options, callback) {
  2712. _checkContext(this, 'create');
  2713. let args;
  2714. let cb;
  2715. const discriminatorKey = this.schema.options.discriminatorKey;
  2716. if (Array.isArray(doc)) {
  2717. args = doc;
  2718. cb = typeof options === 'function' ? options : callback;
  2719. options = options != null && typeof options === 'object' ? options : {};
  2720. } else {
  2721. const last = arguments[arguments.length - 1];
  2722. options = {};
  2723. // Handle falsy callbacks re: #5061
  2724. if (typeof last === 'function' || (arguments.length > 1 && !last)) {
  2725. args = [...arguments];
  2726. cb = args.pop();
  2727. } else {
  2728. args = [...arguments];
  2729. }
  2730. if (args.length === 2 &&
  2731. args[0] != null &&
  2732. args[1] != null &&
  2733. args[0].session == null &&
  2734. getConstructorName(last.session) === 'ClientSession' &&
  2735. !this.schema.path('session')) {
  2736. // Probably means the user is running into the common mistake of trying
  2737. // to use a spread to specify options, see gh-7535
  2738. utils.warn('WARNING: to pass a `session` to `Model.create()` in ' +
  2739. 'Mongoose, you **must** pass an array as the first argument. See: ' +
  2740. 'https://mongoosejs.com/docs/api.html#model_Model.create');
  2741. }
  2742. }
  2743. return this.db.base._promiseOrCallback(cb, cb => {
  2744. cb = this.$wrapCallback(cb);
  2745. if (args.length === 0) {
  2746. if (Array.isArray(doc)) {
  2747. return cb(null, []);
  2748. } else {
  2749. return cb(null);
  2750. }
  2751. }
  2752. const toExecute = [];
  2753. let firstError;
  2754. args.forEach(doc => {
  2755. toExecute.push(callback => {
  2756. const Model = this.discriminators && doc[discriminatorKey] != null ?
  2757. this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
  2758. this;
  2759. if (Model == null) {
  2760. throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
  2761. `found for model "${this.modelName}"`);
  2762. }
  2763. let toSave = doc;
  2764. const callbackWrapper = (error, doc) => {
  2765. if (error) {
  2766. if (!firstError) {
  2767. firstError = error;
  2768. }
  2769. return callback(null, { error: error });
  2770. }
  2771. callback(null, { doc: doc });
  2772. };
  2773. if (!(toSave instanceof Model)) {
  2774. try {
  2775. toSave = new Model(toSave);
  2776. } catch (error) {
  2777. return callbackWrapper(error);
  2778. }
  2779. }
  2780. toSave.$save(options, callbackWrapper);
  2781. });
  2782. });
  2783. let numFns = toExecute.length;
  2784. if (numFns === 0) {
  2785. return cb(null, []);
  2786. }
  2787. const _done = (error, res) => {
  2788. const savedDocs = [];
  2789. const len = res.length;
  2790. for (let i = 0; i < len; ++i) {
  2791. if (res[i].doc) {
  2792. savedDocs.push(res[i].doc);
  2793. }
  2794. }
  2795. if (firstError) {
  2796. return cb(firstError, savedDocs);
  2797. }
  2798. if (doc instanceof Array) {
  2799. cb(null, savedDocs);
  2800. } else {
  2801. cb.apply(this, [null].concat(savedDocs));
  2802. }
  2803. };
  2804. const _res = [];
  2805. toExecute.forEach((fn, i) => {
  2806. fn((err, res) => {
  2807. _res[i] = res;
  2808. if (--numFns <= 0) {
  2809. return _done(null, _res);
  2810. }
  2811. });
  2812. });
  2813. }, this.events);
  2814. };
  2815. /**
  2816. * _Requires a replica set running MongoDB >= 3.6.0._ Watches the
  2817. * underlying collection for changes using
  2818. * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/).
  2819. *
  2820. * This function does **not** trigger any middleware. In particular, it
  2821. * does **not** trigger aggregate middleware.
  2822. *
  2823. * The ChangeStream object is an event emitter that emits the following events:
  2824. *
  2825. * - 'change': A change occurred, see below example
  2826. * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates.
  2827. * - 'end': Emitted if the underlying stream is closed
  2828. * - 'close': Emitted if the underlying stream is closed
  2829. *
  2830. * ####Example:
  2831. *
  2832. * const doc = await Person.create({ name: 'Ned Stark' });
  2833. * const changeStream = Person.watch().on('change', change => console.log(change));
  2834. * // Will print from the above `console.log()`:
  2835. * // { _id: { _data: ... },
  2836. * // operationType: 'delete',
  2837. * // ns: { db: 'mydb', coll: 'Person' },
  2838. * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } }
  2839. * await doc.remove();
  2840. *
  2841. * @param {Array} [pipeline]
  2842. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch)
  2843. * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter
  2844. * @api public
  2845. */
  2846. Model.watch = function(pipeline, options) {
  2847. _checkContext(this, 'watch');
  2848. const changeStreamThunk = cb => {
  2849. pipeline = pipeline || [];
  2850. prepareDiscriminatorPipeline(pipeline, this.schema, 'fullDocument');
  2851. if (this.$__collection.buffer) {
  2852. this.$__collection.addQueue(() => {
  2853. if (this.closed) {
  2854. return;
  2855. }
  2856. const driverChangeStream = this.$__collection.watch(pipeline, options);
  2857. cb(null, driverChangeStream);
  2858. });
  2859. } else {
  2860. const driverChangeStream = this.$__collection.watch(pipeline, options);
  2861. cb(null, driverChangeStream);
  2862. }
  2863. };
  2864. return new ChangeStream(changeStreamThunk, pipeline, options);
  2865. };
  2866. /**
  2867. * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
  2868. * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
  2869. * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
  2870. *
  2871. * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`.
  2872. *
  2873. * This function does not trigger any middleware.
  2874. *
  2875. * ####Example:
  2876. *
  2877. * const session = await Person.startSession();
  2878. * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
  2879. * await doc.remove();
  2880. * // `doc` will always be null, even if reading from a replica set
  2881. * // secondary. Without causal consistency, it is possible to
  2882. * // get a doc back from the below query if the query reads from a
  2883. * // secondary that is experiencing replication lag.
  2884. * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
  2885. *
  2886. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
  2887. * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
  2888. * @param {Function} [callback]
  2889. * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
  2890. * @api public
  2891. */
  2892. Model.startSession = function() {
  2893. _checkContext(this, 'startSession');
  2894. return this.db.startSession.apply(this.db, arguments);
  2895. };
  2896. /**
  2897. * Shortcut for validating an array of documents and inserting them into
  2898. * MongoDB if they're all valid. This function is faster than `.create()`
  2899. * because it only sends one operation to the server, rather than one for each
  2900. * document.
  2901. *
  2902. * Mongoose always validates each document **before** sending `insertMany`
  2903. * to MongoDB. So if one document has a validation error, no documents will
  2904. * be saved, unless you set
  2905. * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling).
  2906. *
  2907. * This function does **not** trigger save middleware.
  2908. *
  2909. * This function triggers the following middleware.
  2910. *
  2911. * - `insertMany()`
  2912. *
  2913. * ####Example:
  2914. *
  2915. * const arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
  2916. * Movies.insertMany(arr, function(error, docs) {});
  2917. *
  2918. * @param {Array|Object|*} doc(s)
  2919. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany)
  2920. * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`.
  2921. * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`.
  2922. * @param {Boolean} [options.lean = false] if `true`, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting.
  2923. * @param {Number} [options.limit = null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory.
  2924. * @param {String|Object|Array} [options.populate = null] populates the result documents. This option is a no-op if `rawResult` is set.
  2925. * @param {Function} [callback] callback
  2926. * @return {Promise} resolving to the raw result from the MongoDB driver if `options.rawResult` was `true`, or the documents that passed validation, otherwise
  2927. * @api public
  2928. */
  2929. Model.insertMany = function(arr, options, callback) {
  2930. _checkContext(this, 'insertMany');
  2931. if (typeof options === 'function') {
  2932. callback = options;
  2933. options = null;
  2934. }
  2935. return this.db.base._promiseOrCallback(callback, cb => {
  2936. this.$__insertMany(arr, options, cb);
  2937. }, this.events);
  2938. };
  2939. /*!
  2940. * ignore
  2941. */
  2942. Model.$__insertMany = function(arr, options, callback) {
  2943. const _this = this;
  2944. if (typeof options === 'function') {
  2945. callback = options;
  2946. options = null;
  2947. }
  2948. if (callback) {
  2949. callback = this.$handleCallbackError(callback);
  2950. callback = this.$wrapCallback(callback);
  2951. }
  2952. callback = callback || utils.noop;
  2953. options = options || {};
  2954. const limit = get(options, 'limit', 1000);
  2955. const rawResult = get(options, 'rawResult', false);
  2956. const ordered = get(options, 'ordered', true);
  2957. const lean = get(options, 'lean', false);
  2958. if (!Array.isArray(arr)) {
  2959. arr = [arr];
  2960. }
  2961. const validationErrors = [];
  2962. const toExecute = arr.map(doc =>
  2963. callback => {
  2964. if (!(doc instanceof _this)) {
  2965. try {
  2966. doc = new _this(doc);
  2967. } catch (err) {
  2968. return callback(err);
  2969. }
  2970. }
  2971. if (options.session != null) {
  2972. doc.$session(options.session);
  2973. }
  2974. // If option `lean` is set to true bypass validation
  2975. if (lean) {
  2976. // we have to execute callback at the nextTick to be compatible
  2977. // with parallelLimit, as `results` variable has TDZ issue if we
  2978. // execute the callback synchronously
  2979. return immediate(() => callback(null, doc));
  2980. }
  2981. doc.$validate({ __noPromise: true }, function(error) {
  2982. if (error) {
  2983. // Option `ordered` signals that insert should be continued after reaching
  2984. // a failing insert. Therefore we delegate "null", meaning the validation
  2985. // failed. It's up to the next function to filter out all failed models
  2986. if (ordered === false) {
  2987. validationErrors.push(error);
  2988. return callback(null, null);
  2989. }
  2990. return callback(error);
  2991. }
  2992. callback(null, doc);
  2993. });
  2994. });
  2995. parallelLimit(toExecute, limit, function(error, docs) {
  2996. if (error) {
  2997. callback(error, null);
  2998. return;
  2999. }
  3000. // We filter all failed pre-validations by removing nulls
  3001. const docAttributes = docs.filter(function(doc) {
  3002. return doc != null;
  3003. });
  3004. // Quickly escape while there aren't any valid docAttributes
  3005. if (docAttributes.length === 0) {
  3006. if (rawResult) {
  3007. const res = {
  3008. mongoose: {
  3009. validationErrors: validationErrors
  3010. }
  3011. };
  3012. return callback(null, res);
  3013. }
  3014. callback(null, []);
  3015. return;
  3016. }
  3017. const docObjects = docAttributes.map(function(doc) {
  3018. if (doc.$__schema.options.versionKey) {
  3019. doc[doc.$__schema.options.versionKey] = 0;
  3020. }
  3021. if (doc.initializeTimestamps) {
  3022. return doc.initializeTimestamps().toObject(internalToObjectOptions);
  3023. }
  3024. return doc.toObject(internalToObjectOptions);
  3025. });
  3026. _this.$__collection.insertMany(docObjects, options, function(error, res) {
  3027. if (error) {
  3028. // `writeErrors` is a property reported by the MongoDB driver,
  3029. // just not if there's only 1 error.
  3030. if (error.writeErrors == null &&
  3031. get(error, 'result.result.writeErrors') != null) {
  3032. error.writeErrors = error.result.result.writeErrors;
  3033. }
  3034. // `insertedDocs` is a Mongoose-specific property
  3035. const erroredIndexes = new Set(get(error, 'writeErrors', []).map(err => err.index));
  3036. let firstErroredIndex = -1;
  3037. error.insertedDocs = docAttributes.
  3038. filter((doc, i) => {
  3039. const isErrored = erroredIndexes.has(i);
  3040. if (ordered) {
  3041. if (firstErroredIndex > -1) {
  3042. return i < firstErroredIndex;
  3043. }
  3044. if (isErrored) {
  3045. firstErroredIndex = i;
  3046. }
  3047. }
  3048. return !isErrored;
  3049. }).
  3050. map(function setIsNewForInsertedDoc(doc) {
  3051. doc.$__reset();
  3052. _setIsNew(doc, false);
  3053. return doc;
  3054. });
  3055. callback(error, null);
  3056. return;
  3057. }
  3058. for (const attribute of docAttributes) {
  3059. attribute.$__reset();
  3060. _setIsNew(attribute, false);
  3061. }
  3062. if (rawResult) {
  3063. if (ordered === false) {
  3064. // Decorate with mongoose validation errors in case of unordered,
  3065. // because then still do `insertMany()`
  3066. res.mongoose = {
  3067. validationErrors: validationErrors
  3068. };
  3069. }
  3070. return callback(null, res);
  3071. }
  3072. if (options.populate != null) {
  3073. return _this.populate(docAttributes, options.populate, err => {
  3074. if (err != null) {
  3075. error.insertedDocs = docAttributes;
  3076. return callback(err);
  3077. }
  3078. callback(null, docs);
  3079. });
  3080. }
  3081. callback(null, docAttributes);
  3082. });
  3083. });
  3084. };
  3085. /*!
  3086. * ignore
  3087. */
  3088. function _setIsNew(doc, val) {
  3089. doc.$isNew = val;
  3090. doc.$emit('isNew', val);
  3091. doc.constructor.emit('isNew', val);
  3092. const subdocs = doc.$getAllSubdocs();
  3093. for (const subdoc of subdocs) {
  3094. subdoc.$isNew = val;
  3095. }
  3096. }
  3097. /**
  3098. * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`,
  3099. * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one
  3100. * command. This is faster than sending multiple independent operations (e.g.
  3101. * if you use `create()`) because with `bulkWrite()` there is only one round
  3102. * trip to MongoDB.
  3103. *
  3104. * Mongoose will perform casting on all operations you provide.
  3105. *
  3106. * This function does **not** trigger any middleware, neither `save()`, nor `update()`.
  3107. * If you need to trigger
  3108. * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead.
  3109. *
  3110. * ####Example:
  3111. *
  3112. * Character.bulkWrite([
  3113. * {
  3114. * insertOne: {
  3115. * document: {
  3116. * name: 'Eddard Stark',
  3117. * title: 'Warden of the North'
  3118. * }
  3119. * }
  3120. * },
  3121. * {
  3122. * updateOne: {
  3123. * filter: { name: 'Eddard Stark' },
  3124. * // If you were using the MongoDB driver directly, you'd need to do
  3125. * // `update: { $set: { title: ... } }` but mongoose adds $set for
  3126. * // you.
  3127. * update: { title: 'Hand of the King' }
  3128. * }
  3129. * },
  3130. * {
  3131. * deleteOne: {
  3132. * {
  3133. * filter: { name: 'Eddard Stark' }
  3134. * }
  3135. * }
  3136. * }
  3137. * ]).then(res => {
  3138. * // Prints "1 1 1"
  3139. * console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
  3140. * });
  3141. *
  3142. * The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are:
  3143. *
  3144. * - `insertOne`
  3145. * - `updateOne`
  3146. * - `updateMany`
  3147. * - `deleteOne`
  3148. * - `deleteMany`
  3149. * - `replaceOne`
  3150. *
  3151. * @param {Array} ops
  3152. * @param {Object} [ops.insertOne.document] The document to insert
  3153. * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter
  3154. * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
  3155. * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match
  3156. * @param {Boolean} [opts.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation
  3157. * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
  3158. * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
  3159. * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter
  3160. * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
  3161. * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter`
  3162. * @param {Boolean} [opts.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation
  3163. * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
  3164. * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
  3165. * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter
  3166. * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter
  3167. * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter
  3168. * @param {Object} [opts.replaceOne.replacement] The replacement document
  3169. * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter`
  3170. * @param {Object} [options]
  3171. * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.
  3172. * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html).
  3173. * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information.
  3174. * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout).
  3175. * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option)
  3176. * @param {Boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk.
  3177. * @param {Boolean} [options.strict=null] Overwrites the [`strict` option](/docs/guide.html#strict) on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk.
  3178. * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}`
  3179. * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds
  3180. * @api public
  3181. */
  3182. Model.bulkWrite = function(ops, options, callback) {
  3183. _checkContext(this, 'bulkWrite');
  3184. if (typeof options === 'function') {
  3185. callback = options;
  3186. options = null;
  3187. }
  3188. options = options || {};
  3189. const validations = ops.map(op => castBulkWrite(this, op, options));
  3190. callback = this.$handleCallbackError(callback);
  3191. return this.db.base._promiseOrCallback(callback, cb => {
  3192. cb = this.$wrapCallback(cb);
  3193. each(validations, (fn, cb) => fn(cb), error => {
  3194. if (error) {
  3195. return cb(error);
  3196. }
  3197. if (ops.length === 0) {
  3198. return cb(null, getDefaultBulkwriteResult());
  3199. }
  3200. this.$__collection.bulkWrite(ops, options, (error, res) => {
  3201. if (error) {
  3202. return cb(error);
  3203. }
  3204. cb(null, res);
  3205. });
  3206. });
  3207. }, this.events);
  3208. };
  3209. /**
  3210. * takes an array of documents, gets the changes and inserts/updates documents in the database
  3211. * according to whether or not the document is new, or whether it has changes or not.
  3212. *
  3213. * `bulkSave` uses `bulkWrite` under the hood, so it's mostly useful when dealing with many documents (10K+)
  3214. *
  3215. * @param {[Document]} documents
  3216. * @param {Object} [options] options passed to the underlying `bulkWrite()`
  3217. * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html).
  3218. * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information.
  3219. * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout).
  3220. * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option)
  3221. *
  3222. */
  3223. Model.bulkSave = function(documents, options) {
  3224. const preSavePromises = documents.map(buildPreSavePromise);
  3225. const writeOperations = this.buildBulkWriteOperations(documents, { skipValidation: true });
  3226. let bulkWriteResultPromise;
  3227. return Promise.all(preSavePromises)
  3228. .then(() => bulkWriteResultPromise = this.bulkWrite(writeOperations, options))
  3229. .then(() => documents.map(buildSuccessfulWriteHandlerPromise))
  3230. .then(() => bulkWriteResultPromise)
  3231. .catch((err) => {
  3232. if (!get(err, 'writeErrors.length')) {
  3233. throw err;
  3234. }
  3235. return Promise.all(
  3236. documents.map((document) => {
  3237. const documentError = err.writeErrors.find(writeError => {
  3238. const writeErrorDocumentId = writeError.err.op._id || writeError.err.op.q._id;
  3239. return writeErrorDocumentId.toString() === document._id.toString();
  3240. });
  3241. if (documentError == null) {
  3242. return buildSuccessfulWriteHandlerPromise(document);
  3243. }
  3244. })
  3245. ).then(() => {
  3246. throw err;
  3247. });
  3248. });
  3249. };
  3250. function buildPreSavePromise(document) {
  3251. return new Promise((resolve, reject) => {
  3252. document.schema.s.hooks.execPre('save', document, (err) => {
  3253. if (err) {
  3254. reject(err);
  3255. return;
  3256. }
  3257. resolve();
  3258. });
  3259. });
  3260. }
  3261. function buildSuccessfulWriteHandlerPromise(document) {
  3262. return new Promise((resolve, reject) => {
  3263. handleSuccessfulWrite(document, resolve, reject);
  3264. });
  3265. }
  3266. function handleSuccessfulWrite(document, resolve, reject) {
  3267. if (document.$isNew) {
  3268. _setIsNew(document, false);
  3269. }
  3270. document.$__reset();
  3271. document.schema.s.hooks.execPost('save', document, {}, (err) => {
  3272. if (err) {
  3273. reject(err);
  3274. return;
  3275. }
  3276. resolve();
  3277. });
  3278. }
  3279. /**
  3280. *
  3281. * @param {[Document]} documents The array of documents to build write operations of
  3282. * @param {Object} options
  3283. * @param {Boolean} options.skipValidation defaults to `false`, when set to true, building the write operations will bypass validating the documents.
  3284. * @returns
  3285. */
  3286. Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, options) {
  3287. if (!Array.isArray(documents)) {
  3288. throw new Error(`bulkSave expects an array of documents to be passed, received \`${documents}\` instead`);
  3289. }
  3290. setDefaultOptions();
  3291. const writeOperations = documents.reduce((accumulator, document, i) => {
  3292. if (!options.skipValidation) {
  3293. if (!(document instanceof Document)) {
  3294. throw new Error(`documents.${i} was not a mongoose document, documents must be an array of mongoose documents (instanceof mongoose.Document).`);
  3295. }
  3296. const validationError = document.validateSync();
  3297. if (validationError) {
  3298. throw validationError;
  3299. }
  3300. }
  3301. const isANewDocument = document.isNew;
  3302. if (isANewDocument) {
  3303. accumulator.push({
  3304. insertOne: { document }
  3305. });
  3306. return accumulator;
  3307. }
  3308. const delta = document.$__delta();
  3309. const isDocumentWithChanges = delta != null && !utils.isEmptyObject(delta[0]);
  3310. if (isDocumentWithChanges) {
  3311. const where = document.$__where(delta[0]);
  3312. const changes = delta[1];
  3313. _applyCustomWhere(document, where);
  3314. document.$__version(where, delta);
  3315. accumulator.push({
  3316. updateOne: {
  3317. filter: where,
  3318. update: changes
  3319. }
  3320. });
  3321. return accumulator;
  3322. }
  3323. return accumulator;
  3324. }, []);
  3325. return writeOperations;
  3326. function setDefaultOptions() {
  3327. options = options || {};
  3328. if (options.skipValidation == null) {
  3329. options.skipValidation = false;
  3330. }
  3331. }
  3332. };
  3333. /**
  3334. * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
  3335. * The document returned has no paths marked as modified initially.
  3336. *
  3337. * ####Example:
  3338. *
  3339. * // hydrate previous data into a Mongoose document
  3340. * const mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
  3341. *
  3342. * @param {Object} obj
  3343. * @param {Object|String|Array<String>} [projection] optional projection containing which fields should be selected for this document
  3344. * @return {Document} document instance
  3345. * @api public
  3346. */
  3347. Model.hydrate = function(obj, projection) {
  3348. _checkContext(this, 'hydrate');
  3349. const document = require('./queryhelpers').createModel(this, obj, projection);
  3350. document.$init(obj);
  3351. return document;
  3352. };
  3353. /**
  3354. * Updates one document in the database without returning it.
  3355. *
  3356. * This function triggers the following middleware.
  3357. *
  3358. * - `update()`
  3359. *
  3360. * This method is deprecated. See [Deprecation Warnings](../deprecations.html#update) for details.
  3361. *
  3362. * ####Examples:
  3363. *
  3364. * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
  3365. *
  3366. * const res = await MyModel.update({ name: 'Tobi' }, { ferret: true });
  3367. * res.n; // Number of documents that matched `{ name: 'Tobi' }`
  3368. * // Number of documents that were changed. If every doc matched already
  3369. * // had `ferret` set to `true`, `nModified` will be 0.
  3370. * res.nModified;
  3371. *
  3372. * ####Valid options:
  3373. *
  3374. * - `strict` (boolean): overrides the [schema-level `strict` option](/docs/guide.html#strict) for this update
  3375. * - `upsert` (boolean): whether to create the doc if it doesn't match (false)
  3376. * - `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3377. * - `multi` (boolean): whether multiple documents should be updated (false)
  3378. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  3379. * - `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/).
  3380. * - `timestamps` (boolean): If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  3381. * - `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false)
  3382. *
  3383. * All `update` values are cast to their appropriate SchemaTypes before being sent.
  3384. *
  3385. * The `callback` function receives `(err, rawResponse)`.
  3386. *
  3387. * - `err` is the error if any occurred
  3388. * - `rawResponse` is the full response from Mongo
  3389. *
  3390. * ####Note:
  3391. *
  3392. * All top level keys which are not `atomic` operation names are treated as set operations:
  3393. *
  3394. * ####Example:
  3395. *
  3396. * const query = { name: 'borne' };
  3397. * Model.update(query, { name: 'jason bourne' }, options, callback);
  3398. *
  3399. * // is sent as
  3400. * Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res));
  3401. * // if overwrite option is false. If overwrite is true, sent without the $set wrapper.
  3402. *
  3403. * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`.
  3404. *
  3405. * ####Note:
  3406. *
  3407. * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error.
  3408. *
  3409. * @deprecated
  3410. * @see strict http://mongoosejs.com/docs/guide.html#strict
  3411. * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output
  3412. * @param {Object} filter
  3413. * @param {Object} doc
  3414. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](/docs/api.html#query_Query-setOptions)
  3415. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](/docs/guide.html#strict)
  3416. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3417. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3418. * @param {Boolean} [options.multi=false] whether multiple documents should be updated or just the first one that matches `filter`.
  3419. * @param {Boolean} [options.runValidators=false] if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
  3420. * @param {Boolean} [options.setDefaultsOnInsert=false] `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created.
  3421. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  3422. * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`.
  3423. * @param {Function} [callback] params are (error, [updateWriteOpResult](https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult))
  3424. * @param {Function} [callback]
  3425. * @return {Query}
  3426. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3427. * @see writeOpResult https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpResult
  3428. * @see Query docs https://mongoosejs.com/docs/queries.html
  3429. * @api public
  3430. */
  3431. Model.update = function update(conditions, doc, options, callback) {
  3432. _checkContext(this, 'update');
  3433. return _update(this, 'update', conditions, doc, options, callback);
  3434. };
  3435. /**
  3436. * Same as `update()`, except MongoDB will update _all_ documents that match
  3437. * `filter` (as opposed to just the first one) regardless of the value of
  3438. * the `multi` option.
  3439. *
  3440. * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')`
  3441. * and `post('updateMany')` instead.
  3442. *
  3443. * ####Example:
  3444. * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
  3445. * res.matchedCount; // Number of documents matched
  3446. * res.modifiedCount; // Number of documents modified
  3447. * res.acknowledged; // Boolean indicating everything went smoothly.
  3448. * res.upsertedId; // null or an id containing a document that had to be upserted.
  3449. * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
  3450. *
  3451. * This function triggers the following middleware.
  3452. *
  3453. * - `updateMany()`
  3454. *
  3455. * @param {Object} filter
  3456. * @param {Object|Array} update
  3457. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  3458. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3459. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3460. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3461. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  3462. * @param {Function} [callback] `function(error, res) {}` where `res` has 5 properties: `modifiedCount`, `matchedCount`, `acknowledged`, `upsertedId`, and `upsertedCount`.
  3463. * @return {Query}
  3464. * @see Query docs https://mongoosejs.com/docs/queries.html
  3465. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3466. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3467. * @api public
  3468. */
  3469. Model.updateMany = function updateMany(conditions, doc, options, callback) {
  3470. _checkContext(this, 'updateMany');
  3471. return _update(this, 'updateMany', conditions, doc, options, callback);
  3472. };
  3473. /**
  3474. * Same as `update()`, except it does not support the `multi` or `overwrite`
  3475. * options.
  3476. *
  3477. * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option.
  3478. * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`.
  3479. *
  3480. * ####Example:
  3481. * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
  3482. * res.matchedCount; // Number of documents matched
  3483. * res.modifiedCount; // Number of documents modified
  3484. * res.acknowledged; // Boolean indicating everything went smoothly.
  3485. * res.upsertedId; // null or an id containing a document that had to be upserted.
  3486. * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
  3487. *
  3488. * This function triggers the following middleware.
  3489. *
  3490. * - `updateOne()`
  3491. *
  3492. * @param {Object} filter
  3493. * @param {Object|Array} update
  3494. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  3495. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3496. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3497. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3498. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
  3499. * @param {Function} [callback] params are (error, writeOpResult)
  3500. * @return {Query}
  3501. * @see Query docs https://mongoosejs.com/docs/queries.html
  3502. * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output
  3503. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3504. * @api public
  3505. */
  3506. Model.updateOne = function updateOne(conditions, doc, options, callback) {
  3507. _checkContext(this, 'updateOne');
  3508. return _update(this, 'updateOne', conditions, doc, options, callback);
  3509. };
  3510. /**
  3511. * Same as `update()`, except MongoDB replace the existing document with the
  3512. * given document (no atomic operators like `$set`).
  3513. *
  3514. * ####Example:
  3515. * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
  3516. * res.matchedCount; // Number of documents matched
  3517. * res.modifiedCount; // Number of documents modified
  3518. * res.acknowledged; // Boolean indicating everything went smoothly.
  3519. * res.upsertedId; // null or an id containing a document that had to be upserted.
  3520. * res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
  3521. *
  3522. * This function triggers the following middleware.
  3523. *
  3524. * - `replaceOne()`
  3525. *
  3526. * @param {Object} filter
  3527. * @param {Object} doc
  3528. * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions)
  3529. * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict)
  3530. * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document
  3531. * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern)
  3532. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  3533. * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`.
  3534. * @return {Query}
  3535. * @see Query docs https://mongoosejs.com/docs/queries.html
  3536. * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult
  3537. * @return {Query}
  3538. * @api public
  3539. */
  3540. Model.replaceOne = function replaceOne(conditions, doc, options, callback) {
  3541. _checkContext(this, 'replaceOne');
  3542. const versionKey = get(this, 'schema.options.versionKey', null);
  3543. if (versionKey && !doc[versionKey]) {
  3544. doc[versionKey] = 0;
  3545. }
  3546. return _update(this, 'replaceOne', conditions, doc, options, callback);
  3547. };
  3548. /*!
  3549. * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()`
  3550. * because they need to do the same thing
  3551. */
  3552. function _update(model, op, conditions, doc, options, callback) {
  3553. const mq = new model.Query({}, {}, model, model.collection);
  3554. callback = model.$handleCallbackError(callback);
  3555. // gh-2406
  3556. // make local deep copy of conditions
  3557. if (conditions instanceof Document) {
  3558. conditions = conditions.toObject();
  3559. } else {
  3560. conditions = utils.clone(conditions);
  3561. }
  3562. options = typeof options === 'function' ? options : utils.clone(options);
  3563. const versionKey = get(model, 'schema.options.versionKey', null);
  3564. _decorateUpdateWithVersionKey(doc, options, versionKey);
  3565. return mq[op](conditions, doc, options, callback);
  3566. }
  3567. /**
  3568. * Executes a mapReduce command.
  3569. *
  3570. * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options.
  3571. *
  3572. * This function does not trigger any middleware.
  3573. *
  3574. * ####Example:
  3575. *
  3576. * const o = {};
  3577. * // `map()` and `reduce()` are run on the MongoDB server, not Node.js,
  3578. * // these functions are converted to strings
  3579. * o.map = function () { emit(this.name, 1) };
  3580. * o.reduce = function (k, vals) { return vals.length };
  3581. * User.mapReduce(o, function (err, results) {
  3582. * console.log(results)
  3583. * })
  3584. *
  3585. * ####Other options:
  3586. *
  3587. * - `query` {Object} query filter object.
  3588. * - `sort` {Object} sort input objects using this key
  3589. * - `limit` {Number} max number of documents
  3590. * - `keeptemp` {Boolean, default:false} keep temporary data
  3591. * - `finalize` {Function} finalize function
  3592. * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution
  3593. * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
  3594. * - `verbose` {Boolean, default:false} provide statistics on job execution time.
  3595. * - `readPreference` {String}
  3596. * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job.
  3597. *
  3598. * ####* out options:
  3599. *
  3600. * - `{inline:1}` the results are returned in an array
  3601. * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection
  3602. * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions
  3603. * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old
  3604. *
  3605. * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](/docs/tutorials/lean.html); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).
  3606. *
  3607. * ####Example:
  3608. *
  3609. * const o = {};
  3610. * // You can also define `map()` and `reduce()` as strings if your
  3611. * // linter complains about `emit()` not being defined
  3612. * o.map = 'function () { emit(this.name, 1) }';
  3613. * o.reduce = 'function (k, vals) { return vals.length }';
  3614. * o.out = { replace: 'createdCollectionNameForResults' }
  3615. * o.verbose = true;
  3616. *
  3617. * User.mapReduce(o, function (err, model, stats) {
  3618. * console.log('map reduce took %d ms', stats.processtime)
  3619. * model.find().where('value').gt(10).exec(function (err, docs) {
  3620. * console.log(docs);
  3621. * });
  3622. * })
  3623. *
  3624. * // `mapReduce()` returns a promise. However, ES6 promises can only
  3625. * // resolve to exactly one value,
  3626. * o.resolveToObject = true;
  3627. * const promise = User.mapReduce(o);
  3628. * promise.then(function (res) {
  3629. * const model = res.model;
  3630. * const stats = res.stats;
  3631. * console.log('map reduce took %d ms', stats.processtime)
  3632. * return model.find().where('value').gt(10).exec();
  3633. * }).then(function (docs) {
  3634. * console.log(docs);
  3635. * }).then(null, handleError).end()
  3636. *
  3637. * @param {Object} o an object specifying map-reduce options
  3638. * @param {Function} [callback] optional callback
  3639. * @see http://www.mongodb.org/display/DOCS/MapReduce
  3640. * @return {Promise}
  3641. * @api public
  3642. */
  3643. Model.mapReduce = function mapReduce(o, callback) {
  3644. _checkContext(this, 'mapReduce');
  3645. callback = this.$handleCallbackError(callback);
  3646. return this.db.base._promiseOrCallback(callback, cb => {
  3647. cb = this.$wrapCallback(cb);
  3648. if (!Model.mapReduce.schema) {
  3649. const opts = { _id: false, id: false, strict: false };
  3650. Model.mapReduce.schema = new Schema({}, opts);
  3651. }
  3652. if (!o.out) o.out = { inline: 1 };
  3653. if (o.verbose !== false) o.verbose = true;
  3654. o.map = String(o.map);
  3655. o.reduce = String(o.reduce);
  3656. if (o.query) {
  3657. let q = new this.Query(o.query);
  3658. q.cast(this);
  3659. o.query = q._conditions;
  3660. q = undefined;
  3661. }
  3662. this.$__collection.mapReduce(null, null, o, (err, res) => {
  3663. if (err) {
  3664. return cb(err);
  3665. }
  3666. if (res.collection) {
  3667. // returned a collection, convert to Model
  3668. const model = Model.compile('_mapreduce_' + res.collection.collectionName,
  3669. Model.mapReduce.schema, res.collection.collectionName, this.db,
  3670. this.base);
  3671. model._mapreduce = true;
  3672. res.model = model;
  3673. return cb(null, res);
  3674. }
  3675. cb(null, res);
  3676. });
  3677. }, this.events);
  3678. };
  3679. /**
  3680. * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection.
  3681. *
  3682. * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned.
  3683. *
  3684. * This function triggers the following middleware.
  3685. *
  3686. * - `aggregate()`
  3687. *
  3688. * ####Example:
  3689. *
  3690. * // Find the max balance of all accounts
  3691. * const res = await Users.aggregate([
  3692. * { $group: { _id: null, maxBalance: { $max: '$balance' }}},
  3693. * { $project: { _id: 0, maxBalance: 1 }}
  3694. * ]);
  3695. *
  3696. * console.log(res); // [ { maxBalance: 98000 } ]
  3697. *
  3698. * // Or use the aggregation pipeline builder.
  3699. * const res = await Users.aggregate().
  3700. * group({ _id: null, maxBalance: { $max: '$balance' } }).
  3701. * project('-id maxBalance').
  3702. * exec();
  3703. * console.log(res); // [ { maxBalance: 98 } ]
  3704. *
  3705. * ####NOTE:
  3706. *
  3707. * - Mongoose does **not** cast aggregation pipelines to the model's schema because `$project` and `$group` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the [mongoose-cast-aggregation plugin](https://github.com/AbdelrahmanHafez/mongoose-cast-aggregation) to enable minimal casting for aggregation pipelines.
  3708. * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  3709. *
  3710. * #### More About Aggregations:
  3711. *
  3712. * - [Mongoose `Aggregate`](/docs/api/aggregate.html)
  3713. * - [An Introduction to Mongoose Aggregate](https://masteringjs.io/tutorials/mongoose/aggregate)
  3714. * - [MongoDB Aggregation docs](http://docs.mongodb.org/manual/applications/aggregation/)
  3715. *
  3716. * @see Aggregate #aggregate_Aggregate
  3717. * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/
  3718. * @param {Array} [pipeline] aggregation pipeline as an array of objects
  3719. * @param {Object} [options] aggregation options
  3720. * @param {Function} [callback]
  3721. * @return {Aggregate}
  3722. * @api public
  3723. */
  3724. Model.aggregate = function aggregate(pipeline, options, callback) {
  3725. _checkContext(this, 'aggregate');
  3726. if (arguments.length > 3 || get(pipeline, 'constructor.name') === 'Object') {
  3727. throw new MongooseError('Mongoose 5.x disallows passing a spread of operators ' +
  3728. 'to `Model.aggregate()`. Instead of ' +
  3729. '`Model.aggregate({ $match }, { $skip })`, do ' +
  3730. '`Model.aggregate([{ $match }, { $skip }])`');
  3731. }
  3732. if (typeof pipeline === 'function') {
  3733. callback = pipeline;
  3734. pipeline = [];
  3735. }
  3736. if (typeof options === 'function') {
  3737. callback = options;
  3738. options = null;
  3739. }
  3740. const aggregate = new Aggregate(pipeline || []);
  3741. aggregate.model(this);
  3742. if (options != null) {
  3743. aggregate.option(options);
  3744. }
  3745. if (typeof callback === 'undefined') {
  3746. return aggregate;
  3747. }
  3748. callback = this.$handleCallbackError(callback);
  3749. callback = this.$wrapCallback(callback);
  3750. aggregate.exec(callback);
  3751. return aggregate;
  3752. };
  3753. /**
  3754. * Casts and validates the given object against this model's schema, passing the
  3755. * given `context` to custom validators.
  3756. *
  3757. * ####Example:
  3758. *
  3759. * const Model = mongoose.model('Test', Schema({
  3760. * name: { type: String, required: true },
  3761. * age: { type: Number, required: true }
  3762. * });
  3763. *
  3764. * try {
  3765. * await Model.validate({ name: null }, ['name'])
  3766. * } catch (err) {
  3767. * err instanceof mongoose.Error.ValidationError; // true
  3768. * Object.keys(err.errors); // ['name']
  3769. * }
  3770. *
  3771. * @param {Object} obj
  3772. * @param {Array} pathsToValidate
  3773. * @param {Object} [context]
  3774. * @param {Function} [callback]
  3775. * @return {Promise|undefined}
  3776. * @api public
  3777. */
  3778. Model.validate = function validate(obj, pathsToValidate, context, callback) {
  3779. if ((arguments.length < 3) || (arguments.length === 3 && typeof arguments[2] === 'function')) {
  3780. // For convenience, if we're validating a document or an object, make `context` default to
  3781. // the model so users don't have to always pass `context`, re: gh-10132, gh-10346
  3782. context = obj;
  3783. }
  3784. return this.db.base._promiseOrCallback(callback, cb => {
  3785. const schema = this.schema;
  3786. let paths = Object.keys(schema.paths);
  3787. if (pathsToValidate != null) {
  3788. const _pathsToValidate = new Set(pathsToValidate);
  3789. paths = paths.filter(p => {
  3790. const pieces = p.split('.');
  3791. let cur = pieces[0];
  3792. for (const piece of pieces) {
  3793. if (_pathsToValidate.has(cur)) {
  3794. return true;
  3795. }
  3796. cur += '.' + piece;
  3797. }
  3798. return _pathsToValidate.has(p);
  3799. });
  3800. }
  3801. for (const path of paths) {
  3802. const schemaType = schema.path(path);
  3803. if (!schemaType || !schemaType.$isMongooseArray) {
  3804. continue;
  3805. }
  3806. const val = get(obj, path);
  3807. pushNestedArrayPaths(val, path);
  3808. }
  3809. let remaining = paths.length;
  3810. let error = null;
  3811. for (const path of paths) {
  3812. const schemaType = schema.path(path);
  3813. if (schemaType == null) {
  3814. _checkDone();
  3815. continue;
  3816. }
  3817. const pieces = path.split('.');
  3818. let cur = obj;
  3819. for (let i = 0; i < pieces.length - 1; ++i) {
  3820. cur = cur[pieces[i]];
  3821. }
  3822. let val = get(obj, path, void 0);
  3823. if (val != null) {
  3824. try {
  3825. val = schemaType.cast(val);
  3826. cur[pieces[pieces.length - 1]] = val;
  3827. } catch (err) {
  3828. error = error || new ValidationError();
  3829. error.addError(path, err);
  3830. _checkDone();
  3831. continue;
  3832. }
  3833. }
  3834. schemaType.doValidate(val, err => {
  3835. if (err) {
  3836. error = error || new ValidationError();
  3837. if (err instanceof ValidationError) {
  3838. for (const _err of Object.keys(err.errors)) {
  3839. error.addError(`${path}.${err.errors[_err].path}`, _err);
  3840. }
  3841. } else {
  3842. error.addError(err.path, err);
  3843. }
  3844. }
  3845. _checkDone();
  3846. }, context, { path: path });
  3847. }
  3848. function pushNestedArrayPaths(nestedArray, path) {
  3849. if (nestedArray == null) {
  3850. return;
  3851. }
  3852. for (let i = 0; i < nestedArray.length; ++i) {
  3853. if (Array.isArray(nestedArray[i])) {
  3854. pushNestedArrayPaths(nestedArray[i], path + '.' + i);
  3855. } else {
  3856. paths.push(path + '.' + i);
  3857. }
  3858. }
  3859. }
  3860. function _checkDone() {
  3861. if (--remaining <= 0) {
  3862. return cb(error);
  3863. }
  3864. }
  3865. });
  3866. };
  3867. /**
  3868. * Populates document references.
  3869. *
  3870. * Changed in Mongoose 6: the model you call `populate()` on should be the
  3871. * "local field" model, **not** the "foreign field" model.
  3872. *
  3873. * ####Available top-level options:
  3874. *
  3875. * - path: space delimited path(s) to populate
  3876. * - select: optional fields to select
  3877. * - match: optional query conditions to match
  3878. * - model: optional name of the model to use for population
  3879. * - options: optional query options like sort, limit, etc
  3880. * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default.
  3881. * - strictPopulate: optional boolean, set to `false` to allow populating paths that aren't in the schema.
  3882. *
  3883. * ####Examples:
  3884. *
  3885. * const Dog = mongoose.model('Dog', new Schema({ name: String, breed: String }));
  3886. * const Person = mongoose.model('Person', new Schema({
  3887. * name: String,
  3888. * pet: { type: mongoose.ObjectId, ref: 'Dog' }
  3889. * }));
  3890. *
  3891. * const pets = await Pet.create([
  3892. * { name: 'Daisy', breed: 'Beagle' },
  3893. * { name: 'Einstein', breed: 'Catalan Sheepdog' }
  3894. * ]);
  3895. *
  3896. * // populate many plain objects
  3897. * const users = [
  3898. * { name: 'John Wick', dog: pets[0]._id },
  3899. * { name: 'Doc Brown', dog: pets[1]._id }
  3900. * ];
  3901. * await User.populate(users, { path: 'dog', select: 'name' });
  3902. * users[0].dog.name; // 'Daisy'
  3903. * users[0].dog.breed; // undefined because of `select`
  3904. *
  3905. * @param {Document|Array} docs Either a single document or array of documents to populate.
  3906. * @param {Object|String} options Either the paths to populate or an object specifying all parameters
  3907. * @param {string} [options.path=null] The path to populate.
  3908. * @param {boolean} [options.retainNullValues=false] By default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries.
  3909. * @param {boolean} [options.getters=false] If true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options).
  3910. * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them.
  3911. * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object.
  3912. * @param {Boolean} [options.skipInvalidIds=false] By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type.
  3913. * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents.
  3914. * @param {Boolean} [options.strictPopulate=true] Set to false to allow populating paths that aren't defined in the given model's schema.
  3915. * @param {Object} [options.options=null] Additional options like `limit` and `lean`.
  3916. * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document.
  3917. * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
  3918. * @return {Promise}
  3919. * @api public
  3920. */
  3921. Model.populate = function(docs, paths, callback) {
  3922. _checkContext(this, 'populate');
  3923. const _this = this;
  3924. // normalized paths
  3925. paths = utils.populate(paths);
  3926. // data that should persist across subPopulate calls
  3927. const cache = {};
  3928. callback = this.$handleCallbackError(callback);
  3929. return this.db.base._promiseOrCallback(callback, cb => {
  3930. cb = this.$wrapCallback(cb);
  3931. _populate(_this, docs, paths, cache, cb);
  3932. }, this.events);
  3933. };
  3934. /*!
  3935. * Populate helper
  3936. *
  3937. * @param {Model} model the model to use
  3938. * @param {Document|Array} docs Either a single document or array of documents to populate.
  3939. * @param {Object} paths
  3940. * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
  3941. * @return {Function}
  3942. * @api private
  3943. */
  3944. function _populate(model, docs, paths, cache, callback) {
  3945. let pending = paths.length;
  3946. if (paths.length === 0) {
  3947. return callback(null, docs);
  3948. }
  3949. // each path has its own query options and must be executed separately
  3950. for (const path of paths) {
  3951. populate(model, docs, path, next);
  3952. }
  3953. function next(err) {
  3954. if (err) {
  3955. return callback(err, null);
  3956. }
  3957. if (--pending) {
  3958. return;
  3959. }
  3960. callback(null, docs);
  3961. }
  3962. }
  3963. /*!
  3964. * Populates `docs`
  3965. */
  3966. const excludeIdReg = /\s?-_id\s?/;
  3967. const excludeIdRegGlobal = /\s?-_id\s?/g;
  3968. function populate(model, docs, options, callback) {
  3969. const populateOptions = { ...options };
  3970. if (options.strictPopulate == null) {
  3971. if (options._localModel != null && options._localModel.schema._userProvidedOptions.strictPopulate != null) {
  3972. populateOptions.strictPopulate = options._localModel.schema._userProvidedOptions.strictPopulate;
  3973. } else if (options._localModel != null && model.base.options.strictPopulate != null) {
  3974. populateOptions.strictPopulate = model.base.options.strictPopulate;
  3975. } else if (model.base.options.strictPopulate != null) {
  3976. populateOptions.strictPopulate = model.base.options.strictPopulate;
  3977. }
  3978. }
  3979. // normalize single / multiple docs passed
  3980. if (!Array.isArray(docs)) {
  3981. docs = [docs];
  3982. }
  3983. if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) {
  3984. return callback();
  3985. }
  3986. const modelsMap = getModelsMapForPopulate(model, docs, populateOptions);
  3987. if (modelsMap instanceof MongooseError) {
  3988. return immediate(function() {
  3989. callback(modelsMap);
  3990. });
  3991. }
  3992. const len = modelsMap.length;
  3993. let vals = [];
  3994. function flatten(item) {
  3995. // no need to include undefined values in our query
  3996. return undefined !== item;
  3997. }
  3998. let _remaining = len;
  3999. let hasOne = false;
  4000. const params = [];
  4001. for (let i = 0; i < len; ++i) {
  4002. const mod = modelsMap[i];
  4003. let select = mod.options.select;
  4004. let ids = utils.array.flatten(mod.ids, flatten);
  4005. ids = utils.array.unique(ids);
  4006. const assignmentOpts = {};
  4007. assignmentOpts.sort = get(mod, 'options.options.sort', void 0);
  4008. assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0);
  4009. if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) {
  4010. // Ensure that we set to 0 or empty array even
  4011. // if we don't actually execute a query to make sure there's a value
  4012. // and we know this path was populated for future sets. See gh-7731, gh-8230
  4013. --_remaining;
  4014. _assign(model, [], mod, assignmentOpts);
  4015. continue;
  4016. }
  4017. hasOne = true;
  4018. const match = createPopulateQueryFilter(ids, mod.match, mod.foreignField, mod.model, mod.options.skipInvalidIds);
  4019. if (assignmentOpts.excludeId) {
  4020. // override the exclusion from the query so we can use the _id
  4021. // for document matching during assignment. we'll delete the
  4022. // _id back off before returning the result.
  4023. if (typeof select === 'string') {
  4024. select = select.replace(excludeIdRegGlobal, ' ');
  4025. } else {
  4026. // preserve original select conditions by copying
  4027. select = utils.object.shallowCopy(select);
  4028. delete select._id;
  4029. }
  4030. }
  4031. if (mod.options.options && mod.options.options.limit != null) {
  4032. assignmentOpts.originalLimit = mod.options.options.limit;
  4033. } else if (mod.options.limit != null) {
  4034. assignmentOpts.originalLimit = mod.options.limit;
  4035. }
  4036. params.push([mod, match, select, assignmentOpts, _next]);
  4037. }
  4038. if (!hasOne) {
  4039. // If models but no docs, skip further deep populate.
  4040. if (modelsMap.length !== 0) {
  4041. return callback();
  4042. }
  4043. // If no models to populate but we have a nested populate,
  4044. // keep trying, re: gh-8946
  4045. if (options.populate != null) {
  4046. const opts = utils.populate(options.populate).map(pop => Object.assign({}, pop, {
  4047. path: options.path + '.' + pop.path
  4048. }));
  4049. return model.populate(docs, opts, callback);
  4050. }
  4051. return callback();
  4052. }
  4053. for (const arr of params) {
  4054. _execPopulateQuery.apply(null, arr);
  4055. }
  4056. function _next(err, valsFromDb) {
  4057. if (err != null) {
  4058. return callback(err, null);
  4059. }
  4060. vals = vals.concat(valsFromDb);
  4061. if (--_remaining === 0) {
  4062. _done();
  4063. }
  4064. }
  4065. function _done() {
  4066. for (const arr of params) {
  4067. const mod = arr[0];
  4068. const assignmentOpts = arr[3];
  4069. for (const val of vals) {
  4070. mod.options._childDocs.push(val);
  4071. }
  4072. _assign(model, vals, mod, assignmentOpts);
  4073. }
  4074. for (const arr of params) {
  4075. removeDeselectedForeignField(arr[0].foreignField, arr[0].options, vals);
  4076. }
  4077. callback();
  4078. }
  4079. }
  4080. /*!
  4081. * ignore
  4082. */
  4083. function _execPopulateQuery(mod, match, select, assignmentOpts, callback) {
  4084. const subPopulate = utils.clone(mod.options.populate);
  4085. const queryOptions = Object.assign({
  4086. skip: mod.options.skip,
  4087. limit: mod.options.limit,
  4088. perDocumentLimit: mod.options.perDocumentLimit
  4089. }, mod.options.options);
  4090. if (mod.count) {
  4091. delete queryOptions.skip;
  4092. }
  4093. if (queryOptions.perDocumentLimit != null) {
  4094. queryOptions.limit = queryOptions.perDocumentLimit;
  4095. delete queryOptions.perDocumentLimit;
  4096. } else if (queryOptions.limit != null) {
  4097. queryOptions.limit = queryOptions.limit * mod.ids.length;
  4098. }
  4099. const query = mod.model.find(match, select, queryOptions);
  4100. // If we're doing virtual populate and projection is inclusive and foreign
  4101. // field is not selected, automatically select it because mongoose needs it.
  4102. // If projection is exclusive and client explicitly unselected the foreign
  4103. // field, that's the client's fault.
  4104. for (const foreignField of mod.foreignField) {
  4105. if (foreignField !== '_id' && query.selectedInclusively() &&
  4106. !isPathSelectedInclusive(query._fields, foreignField)) {
  4107. query.select(foreignField);
  4108. }
  4109. }
  4110. // If using count, still need the `foreignField` so we can match counts
  4111. // to documents, otherwise we would need a separate `count()` for every doc.
  4112. if (mod.count) {
  4113. for (const foreignField of mod.foreignField) {
  4114. query.select(foreignField);
  4115. }
  4116. }
  4117. // If we need to sub-populate, call populate recursively
  4118. if (subPopulate) {
  4119. // If subpopulating on a discriminator, skip check for non-existent
  4120. // paths. Because the discriminator may not have the path defined.
  4121. if (mod.model.baseModelName != null) {
  4122. if (Array.isArray(subPopulate)) {
  4123. subPopulate.forEach(pop => { pop.strictPopulate = false; });
  4124. } else {
  4125. subPopulate.strictPopulate = false;
  4126. }
  4127. }
  4128. const basePath = mod.options._fullPath || mod.options.path;
  4129. if (Array.isArray(subPopulate)) {
  4130. for (const pop of subPopulate) {
  4131. pop._fullPath = basePath + '.' + pop.path;
  4132. }
  4133. } else if (typeof subPopulate === 'object') {
  4134. subPopulate._fullPath = basePath + '.' + subPopulate.path;
  4135. }
  4136. query.populate(subPopulate);
  4137. }
  4138. query.exec((err, docs) => {
  4139. if (err != null) {
  4140. return callback(err);
  4141. }
  4142. for (const val of docs) {
  4143. leanPopulateMap.set(val, mod.model);
  4144. }
  4145. callback(null, docs);
  4146. });
  4147. }
  4148. /*!
  4149. * ignore
  4150. */
  4151. function _assign(model, vals, mod, assignmentOpts) {
  4152. const options = mod.options;
  4153. const isVirtual = mod.isVirtual;
  4154. const justOne = mod.justOne;
  4155. let _val;
  4156. const lean = get(options, 'options.lean', false);
  4157. const len = vals.length;
  4158. const rawOrder = {};
  4159. const rawDocs = {};
  4160. let key;
  4161. let val;
  4162. // Clone because `assignRawDocsToIdStructure` will mutate the array
  4163. const allIds = utils.clone(mod.allIds);
  4164. // optimization:
  4165. // record the document positions as returned by
  4166. // the query result.
  4167. for (let i = 0; i < len; i++) {
  4168. val = vals[i];
  4169. if (val == null) {
  4170. continue;
  4171. }
  4172. for (const foreignField of mod.foreignField) {
  4173. _val = utils.getValue(foreignField, val);
  4174. if (Array.isArray(_val)) {
  4175. _val = utils.array.unique(utils.array.flatten(_val));
  4176. for (let __val of _val) {
  4177. if (__val instanceof Document) {
  4178. __val = __val._id;
  4179. }
  4180. key = String(__val);
  4181. if (rawDocs[key]) {
  4182. if (Array.isArray(rawDocs[key])) {
  4183. rawDocs[key].push(val);
  4184. rawOrder[key].push(i);
  4185. } else {
  4186. rawDocs[key] = [rawDocs[key], val];
  4187. rawOrder[key] = [rawOrder[key], i];
  4188. }
  4189. } else {
  4190. if (isVirtual && !justOne) {
  4191. rawDocs[key] = [val];
  4192. rawOrder[key] = [i];
  4193. } else {
  4194. rawDocs[key] = val;
  4195. rawOrder[key] = i;
  4196. }
  4197. }
  4198. }
  4199. } else {
  4200. if (_val instanceof Document) {
  4201. _val = _val._id;
  4202. }
  4203. key = String(_val);
  4204. if (rawDocs[key]) {
  4205. if (Array.isArray(rawDocs[key])) {
  4206. rawDocs[key].push(val);
  4207. rawOrder[key].push(i);
  4208. } else if (isVirtual ||
  4209. rawDocs[key].constructor !== val.constructor ||
  4210. String(rawDocs[key]._id) !== String(val._id)) {
  4211. // May need to store multiple docs with the same id if there's multiple models
  4212. // if we have discriminators or a ref function. But avoid converting to an array
  4213. // if we have multiple queries on the same model because of `perDocumentLimit` re: gh-9906
  4214. rawDocs[key] = [rawDocs[key], val];
  4215. rawOrder[key] = [rawOrder[key], i];
  4216. }
  4217. } else {
  4218. rawDocs[key] = val;
  4219. rawOrder[key] = i;
  4220. }
  4221. }
  4222. // flag each as result of population
  4223. if (!lean) {
  4224. val.$__.wasPopulated = true;
  4225. }
  4226. }
  4227. }
  4228. assignVals({
  4229. originalModel: model,
  4230. // If virtual, make sure to not mutate original field
  4231. rawIds: mod.isVirtual ? allIds : mod.allIds,
  4232. allIds: allIds,
  4233. unpopulatedValues: mod.unpopulatedValues,
  4234. foreignField: mod.foreignField,
  4235. rawDocs: rawDocs,
  4236. rawOrder: rawOrder,
  4237. docs: mod.docs,
  4238. path: options.path,
  4239. options: assignmentOpts,
  4240. justOne: mod.justOne,
  4241. isVirtual: mod.isVirtual,
  4242. allOptions: mod,
  4243. populatedModel: mod.model,
  4244. lean: lean,
  4245. virtual: mod.virtual,
  4246. count: mod.count,
  4247. match: mod.match
  4248. });
  4249. }
  4250. /*!
  4251. * Compiler utility.
  4252. *
  4253. * @param {String|Function} name model name or class extending Model
  4254. * @param {Schema} schema
  4255. * @param {String} collectionName
  4256. * @param {Connection} connection
  4257. * @param {Mongoose} base mongoose instance
  4258. */
  4259. Model.compile = function compile(name, schema, collectionName, connection, base) {
  4260. const versioningEnabled = schema.options.versionKey !== false;
  4261. if (versioningEnabled && !schema.paths[schema.options.versionKey]) {
  4262. // add versioning to top level documents only
  4263. const o = {};
  4264. o[schema.options.versionKey] = Number;
  4265. schema.add(o);
  4266. }
  4267. let model;
  4268. if (typeof name === 'function' && name.prototype instanceof Model) {
  4269. model = name;
  4270. name = model.name;
  4271. schema.loadClass(model, false);
  4272. model.prototype.$isMongooseModelPrototype = true;
  4273. } else {
  4274. // generate new class
  4275. model = function model(doc, fields, skipId) {
  4276. model.hooks.execPreSync('createModel', doc);
  4277. if (!(this instanceof model)) {
  4278. return new model(doc, fields, skipId);
  4279. }
  4280. const discriminatorKey = model.schema.options.discriminatorKey;
  4281. if (model.discriminators == null || doc == null || doc[discriminatorKey] == null) {
  4282. Model.call(this, doc, fields, skipId);
  4283. return;
  4284. }
  4285. // If discriminator key is set, use the discriminator instead (gh-7586)
  4286. const Discriminator = model.discriminators[doc[discriminatorKey]] ||
  4287. getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]);
  4288. if (Discriminator != null) {
  4289. return new Discriminator(doc, fields, skipId);
  4290. }
  4291. // Otherwise, just use the top-level model
  4292. Model.call(this, doc, fields, skipId);
  4293. };
  4294. }
  4295. model.hooks = schema.s.hooks.clone();
  4296. model.base = base;
  4297. model.modelName = name;
  4298. if (!(model.prototype instanceof Model)) {
  4299. model.__proto__ = Model;
  4300. model.prototype.__proto__ = Model.prototype;
  4301. }
  4302. model.model = function model(name) {
  4303. return this.db.model(name);
  4304. };
  4305. model.db = connection;
  4306. model.prototype.db = connection;
  4307. model.prototype[modelDbSymbol] = connection;
  4308. model.discriminators = model.prototype.discriminators = undefined;
  4309. model[modelSymbol] = true;
  4310. model.events = new EventEmitter();
  4311. schema._preCompile();
  4312. model.prototype.$__setSchema(schema);
  4313. const _userProvidedOptions = schema._userProvidedOptions || {};
  4314. const collectionOptions = {
  4315. schemaUserProvidedOptions: _userProvidedOptions,
  4316. capped: schema.options.capped,
  4317. Promise: model.base.Promise,
  4318. modelName: name
  4319. };
  4320. if (schema.options.autoCreate !== void 0) {
  4321. collectionOptions.autoCreate = schema.options.autoCreate;
  4322. }
  4323. model.prototype.collection = connection.collection(
  4324. collectionName,
  4325. collectionOptions
  4326. );
  4327. model.prototype.$collection = model.prototype.collection;
  4328. model.prototype[modelCollectionSymbol] = model.prototype.collection;
  4329. // apply methods and statics
  4330. applyMethods(model, schema);
  4331. applyStatics(model, schema);
  4332. applyHooks(model, schema);
  4333. applyStaticHooks(model, schema.s.hooks, schema.statics);
  4334. model.schema = model.prototype.$__schema;
  4335. model.collection = model.prototype.collection;
  4336. model.$__collection = model.collection;
  4337. // Create custom query constructor
  4338. model.Query = function() {
  4339. Query.apply(this, arguments);
  4340. };
  4341. model.Query.prototype = Object.create(Query.prototype);
  4342. model.Query.base = Query.base;
  4343. applyQueryMiddleware(model.Query, model);
  4344. applyQueryMethods(model, schema.query);
  4345. return model;
  4346. };
  4347. /*!
  4348. * Register custom query methods for this model
  4349. *
  4350. * @param {Model} model
  4351. * @param {Schema} schema
  4352. */
  4353. function applyQueryMethods(model, methods) {
  4354. for (const i in methods) {
  4355. model.Query.prototype[i] = methods[i];
  4356. }
  4357. }
  4358. /*!
  4359. * Subclass this model with `conn`, `schema`, and `collection` settings.
  4360. *
  4361. * @param {Connection} conn
  4362. * @param {Schema} [schema]
  4363. * @param {String} [collection]
  4364. * @return {Model}
  4365. */
  4366. Model.__subclass = function subclass(conn, schema, collection) {
  4367. // subclass model using this connection and collection name
  4368. const _this = this;
  4369. const Model = function Model(doc, fields, skipId) {
  4370. if (!(this instanceof Model)) {
  4371. return new Model(doc, fields, skipId);
  4372. }
  4373. _this.call(this, doc, fields, skipId);
  4374. };
  4375. Model.__proto__ = _this;
  4376. Model.prototype.__proto__ = _this.prototype;
  4377. Model.db = conn;
  4378. Model.prototype.db = conn;
  4379. Model.prototype[modelDbSymbol] = conn;
  4380. _this[subclassedSymbol] = _this[subclassedSymbol] || [];
  4381. _this[subclassedSymbol].push(Model);
  4382. if (_this.discriminators != null) {
  4383. Model.discriminators = {};
  4384. for (const key of Object.keys(_this.discriminators)) {
  4385. Model.discriminators[key] = _this.discriminators[key].
  4386. __subclass(_this.db, _this.discriminators[key].schema, collection);
  4387. }
  4388. }
  4389. const s = schema && typeof schema !== 'string'
  4390. ? schema
  4391. : _this.prototype.$__schema;
  4392. const options = s.options || {};
  4393. const _userProvidedOptions = s._userProvidedOptions || {};
  4394. if (!collection) {
  4395. collection = _this.prototype.$__schema.get('collection') ||
  4396. utils.toCollectionName(_this.modelName, this.base.pluralize());
  4397. }
  4398. const collectionOptions = {
  4399. schemaUserProvidedOptions: _userProvidedOptions,
  4400. capped: s && options.capped
  4401. };
  4402. Model.prototype.collection = conn.collection(collection, collectionOptions);
  4403. Model.prototype.$collection = Model.prototype.collection;
  4404. Model.prototype[modelCollectionSymbol] = Model.prototype.collection;
  4405. Model.collection = Model.prototype.collection;
  4406. Model.$__collection = Model.collection;
  4407. // Errors handled internally, so ignore
  4408. Model.init(() => {});
  4409. return Model;
  4410. };
  4411. Model.$handleCallbackError = function(callback) {
  4412. if (callback == null) {
  4413. return callback;
  4414. }
  4415. if (typeof callback !== 'function') {
  4416. throw new MongooseError('Callback must be a function, got ' + callback);
  4417. }
  4418. const _this = this;
  4419. return function() {
  4420. immediate(() => {
  4421. try {
  4422. callback.apply(null, arguments);
  4423. } catch (error) {
  4424. _this.emit('error', error);
  4425. }
  4426. });
  4427. };
  4428. };
  4429. /*!
  4430. * ignore
  4431. */
  4432. Model.$wrapCallback = function(callback) {
  4433. const serverSelectionError = new ServerSelectionError();
  4434. const _this = this;
  4435. return function(err) {
  4436. if (err != null && err.name === 'MongoServerSelectionError') {
  4437. arguments[0] = serverSelectionError.assimilateError(err);
  4438. }
  4439. if (err != null && err.name === 'MongoNetworkTimeoutError' && err.message.endsWith('timed out')) {
  4440. _this.db.emit('timeout');
  4441. }
  4442. return callback.apply(null, arguments);
  4443. };
  4444. };
  4445. /**
  4446. * Helper for console.log. Given a model named 'MyModel', returns the string
  4447. * `'Model { MyModel }'`.
  4448. *
  4449. * ####Example:
  4450. *
  4451. * const MyModel = mongoose.model('Test', Schema({ name: String }));
  4452. * MyModel.inspect(); // 'Model { Test }'
  4453. * console.log(MyModel); // Prints 'Model { Test }'
  4454. *
  4455. * @api public
  4456. */
  4457. Model.inspect = function() {
  4458. return `Model { ${this.modelName} }`;
  4459. };
  4460. if (util.inspect.custom) {
  4461. /*!
  4462. * Avoid Node deprecation warning DEP0079
  4463. */
  4464. Model[util.inspect.custom] = Model.inspect;
  4465. }
  4466. /*!
  4467. * Module exports.
  4468. */
  4469. module.exports = exports = Model;