Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • ludda756/TDDD27
1 result
Show changes
Commits on Source (12)
Showing
with 361 additions and 112 deletions
MONGODB_URI=mongodb+srv://TDDD27:jZZQgFI4aRGrGuIw@uploadscluster.delrqyf.mongodb.net/?retryWrites=true&w=majority MONGODB_URI=mongodb+srv://TDDD27:a0mOaDs7yrpTNcoL@uploadscluster.delrqyf.mongodb.net/?retryWrites=true&w=majority
JWT_SECRET=TESTKEYFORTOKEN123 JWT_SECRET=TESTKEYFORTOKEN123
SALT=10 SALT=10
NODE_ENV=development NODE_ENV=development
\ No newline at end of file
...@@ -4,15 +4,19 @@ const cors = require('cors') ...@@ -4,15 +4,19 @@ const cors = require('cors')
require('dotenv').config() require('dotenv').config()
const Routes = require('./routes/routes') const Routes = require('./routes/routes')
const { errorHandler, notFound } = require('./middlewares/errorMiddleware') const { errorHandler, notFound } = require('./middlewares/errorMiddleware')
const checkUserExists = require('./middlewares/MulterMiddleware')
const app = express() const app = express()
//Convert data correctly
app.use(express.json()) app.use(express.json())
app.use(express.static("public")) app.use(express.static("public"))
//Cors is used to connect to the database with react without issues
app.use(cors()) app.use(cors())
app.use(Routes)
app.use(notFound)
app.use(errorHandler)
const PORT = process.env.PORT || 5000 const PORT = process.env.PORT || 5000
...@@ -29,13 +33,7 @@ mongoose.connect(process.env.MONGODB_URI) ...@@ -29,13 +33,7 @@ mongoose.connect(process.env.MONGODB_URI)
.catch(err => console.log(err)) .catch(err => console.log(err))
//Routes
app.use(Routes)
//Error functions
app.use(notFound)
app.use(errorHandler)
const multer = require("multer") const multer = require("multer")
const {v4: uuidv4} = require("uuid") const {v4: uuidv4} = require("uuid")
const path = require("path") const path = require("path")
const userModel = require('../models/user')
const storage = multer.diskStorage({ const storage = multer.diskStorage({
...@@ -20,6 +24,8 @@ const fileFilter = (req,file,cb) => { ...@@ -20,6 +24,8 @@ const fileFilter = (req,file,cb) => {
cb(null,false) cb(null,false)
} }
} }
const uploadMiddleware = multer({storage,fileFilter}) const uploadMiddleware = multer({storage,fileFilter})
module.exports = uploadMiddleware module.exports = uploadMiddleware
\ No newline at end of file
/*const jwt = require('jsonwebtoken');
const config = require('config');
require('dotenv').config()
const auth = (req, res, next) => {
// Get token from header
const token = req.headers['Authorization'];
console.log(token)
// Check if not token
if (!token) {
return res.status(401).json({ msg: 'No token, authorization denied' });
}
try {
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Add user from payload
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({ msg: 'Token is not valid' });
}
}
module.exports = auth;
*/
\ No newline at end of file
const mongoose = require('mongoose') const mongoose = require('mongoose')
const userModel = require('./user')
const postSchema = new mongoose.Schema({ const postSchema = new mongoose.Schema({
name:{ name: {
type:String, type: String,
required:true required: true
},
recipe: {
type: [String],
required: false
},
description: {
type: String,
required: true
},
author:{
type: mongoose.Schema.Types.ObjectId,
ref:"user"
}, },
description:{ profile_picture: {
type:String, type: String,
required:true required: true
}, },
photo:{ profile_name: {
type: String, type: String,
required: true
},
upvotes: {
type: [String],
required: false required: false
},
photo: {
type: String,
required: true
} }
}) })
const postModel = mongoose.model("Post",postSchema) const postModel = mongoose.model("Post", postSchema)
module.exports = postModel module.exports = postModel
...@@ -17,6 +17,15 @@ username:{ ...@@ -17,6 +17,15 @@ username:{
password:{ password:{
type:String, type:String,
required: true required: true
},
posts: {
type: mongoose.SchemaTypes.ObjectId,
ref: "post",
required: false
},
photo:{
type: String,
required: false
} }
},{ },{
timestamps: true, timestamps: true,
......
...@@ -242,12 +242,12 @@ ...@@ -242,12 +242,12 @@
} }
}, },
"node_modules/body-parser": { "node_modules/body-parser": {
"version": "1.20.1", "version": "1.20.2",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz",
"integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==",
"dependencies": { "dependencies": {
"bytes": "3.1.2", "bytes": "3.1.2",
"content-type": "~1.0.4", "content-type": "~1.0.5",
"debug": "2.6.9", "debug": "2.6.9",
"depd": "2.0.0", "depd": "2.0.0",
"destroy": "1.2.0", "destroy": "1.2.0",
...@@ -255,7 +255,7 @@ ...@@ -255,7 +255,7 @@
"iconv-lite": "0.4.24", "iconv-lite": "0.4.24",
"on-finished": "2.4.1", "on-finished": "2.4.1",
"qs": "6.11.0", "qs": "6.11.0",
"raw-body": "2.5.1", "raw-body": "2.5.2",
"type-is": "~1.6.18", "type-is": "~1.6.18",
"unpipe": "1.0.0" "unpipe": "1.0.0"
}, },
...@@ -394,6 +394,17 @@ ...@@ -394,6 +394,17 @@
"typedarray": "^0.0.6" "typedarray": "^0.0.6"
} }
}, },
"node_modules/config": {
"version": "3.3.9",
"resolved": "https://registry.npmjs.org/config/-/config-3.3.9.tgz",
"integrity": "sha512-G17nfe+cY7kR0wVpc49NCYvNtelm/pPy8czHoFkAgtV1lkmcp7DHtWCdDu+C9Z7gb2WVqa9Tm3uF9aKaPbCfhg==",
"dependencies": {
"json5": "^2.2.3"
},
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/console-control-strings": { "node_modules/console-control-strings": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
...@@ -579,6 +590,43 @@ ...@@ -579,6 +590,43 @@
"resolved": "https://registry.npmjs.org/express-async-handler/-/express-async-handler-1.2.0.tgz", "resolved": "https://registry.npmjs.org/express-async-handler/-/express-async-handler-1.2.0.tgz",
"integrity": "sha512-rCSVtPXRmQSW8rmik/AIb2P0op6l7r1fMW538yyvTMltCO4xQEWMmobfrIxN2V1/mVrgxB8Az3reYF6yUZw37w==" "integrity": "sha512-rCSVtPXRmQSW8rmik/AIb2P0op6l7r1fMW538yyvTMltCO4xQEWMmobfrIxN2V1/mVrgxB8Az3reYF6yUZw37w=="
}, },
"node_modules/express/node_modules/body-parser": {
"version": "1.20.1",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz",
"integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==",
"dependencies": {
"bytes": "3.1.2",
"content-type": "~1.0.4",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"on-finished": "2.4.1",
"qs": "6.11.0",
"raw-body": "2.5.1",
"type-is": "~1.6.18",
"unpipe": "1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/express/node_modules/raw-body": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz",
"integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==",
"dependencies": {
"bytes": "3.1.2",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"unpipe": "1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/fill-range": { "node_modules/fill-range": {
"version": "7.0.1", "version": "7.0.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
...@@ -623,6 +671,11 @@ ...@@ -623,6 +671,11 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/fs": {
"version": "0.0.1-security",
"resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
"integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w=="
},
"node_modules/fs-minipass": { "node_modules/fs-minipass": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
...@@ -915,6 +968,17 @@ ...@@ -915,6 +968,17 @@
"joi": ">= 17" "joi": ">= 17"
} }
}, },
"node_modules/json5": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"bin": {
"json5": "lib/cli.js"
},
"engines": {
"node": ">=6"
}
},
"node_modules/jsonwebtoken": { "node_modules/jsonwebtoken": {
"version": "9.0.0", "version": "9.0.0",
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz", "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz",
...@@ -1174,9 +1238,9 @@ ...@@ -1174,9 +1238,9 @@
} }
}, },
"node_modules/mongoose": { "node_modules/mongoose": {
"version": "7.0.3", "version": "7.0.4",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-7.0.3.tgz", "resolved": "https://registry.npmjs.org/mongoose/-/mongoose-7.0.4.tgz",
"integrity": "sha512-3n8vc1/mssuxKa6vfghSocp3MeiCFYzhX36Ok+PsDNNYzHC9tw3rNkAMLemIwZ2jgXqkZ7CfKOxkzjp/d/SWfg==", "integrity": "sha512-MEmQOOqQUvW1PJcji64NtA2EFGHrEvk9o4g//isVYSJW2+8Y8u49C2qFBKzn1t6/l9onQn012o/PcFqR6ixQpQ==",
"dependencies": { "dependencies": {
"bson": "^5.0.1", "bson": "^5.0.1",
"kareem": "2.5.1", "kareem": "2.5.1",
...@@ -1505,9 +1569,9 @@ ...@@ -1505,9 +1569,9 @@
} }
}, },
"node_modules/raw-body": { "node_modules/raw-body": {
"version": "2.5.1", "version": "2.5.2",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
"integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
"dependencies": { "dependencies": {
"bytes": "3.1.2", "bytes": "3.1.2",
"http-errors": "2.0.0", "http-errors": "2.0.0",
......
1.20.2 / 2023-02-21
===================
* Fix strict json error message on Node.js 19+
* deps: content-type@~1.0.5
- perf: skip value escaping when unnecessary
* deps: raw-body@2.5.2
1.20.1 / 2022-10-06 1.20.1 / 2022-10-06
=================== ===================
......
# body-parser # body-parser
[![NPM Version][npm-image]][npm-url] [![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url] [![NPM Downloads][npm-downloads-image]][npm-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url] [![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url] [![Test Coverage][coveralls-image]][coveralls-url]
Node.js body parsing middleware. Node.js body parsing middleware.
...@@ -454,11 +454,12 @@ app.use(bodyParser.text({ type: 'text/html' })) ...@@ -454,11 +454,12 @@ app.use(bodyParser.text({ type: 'text/html' }))
[MIT](LICENSE) [MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/body-parser.svg [ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci
[npm-url]: https://npmjs.org/package/body-parser [ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg [coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master [coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg [node-version-image]: https://badgen.net/npm/node/body-parser
[downloads-url]: https://npmjs.org/package/body-parser [node-version-url]: https://nodejs.org/en/download
[github-actions-ci-image]: https://img.shields.io/github/workflow/status/expressjs/body-parser/ci/master?label=ci [npm-downloads-image]: https://badgen.net/npm/dm/body-parser
[github-actions-ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml [npm-url]: https://npmjs.org/package/body-parser
[npm-version-image]: https://badgen.net/npm/v/body-parser
...@@ -39,6 +39,9 @@ module.exports = json ...@@ -39,6 +39,9 @@ module.exports = json
var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex
var JSON_SYNTAX_CHAR = '#'
var JSON_SYNTAX_REGEXP = /#+/g
/** /**
* Create a middleware to parse JSON bodies. * Create a middleware to parse JSON bodies.
* *
...@@ -152,15 +155,23 @@ function json (options) { ...@@ -152,15 +155,23 @@ function json (options) {
function createStrictSyntaxError (str, char) { function createStrictSyntaxError (str, char) {
var index = str.indexOf(char) var index = str.indexOf(char)
var partial = index !== -1 var partial = ''
? str.substring(0, index) + '#'
: '' if (index !== -1) {
partial = str.substring(0, index) + JSON_SYNTAX_CHAR
for (var i = index + 1; i < str.length; i++) {
partial += JSON_SYNTAX_CHAR
}
}
try { try {
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
} catch (e) { } catch (e) {
return normalizeJsonSyntaxError(e, { return normalizeJsonSyntaxError(e, {
message: e.message.replace('#', char), message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) {
return str.substring(index, index + placeholder.length)
}),
stack: e.stack stack: e.stack
}) })
} }
......
{ {
"name": "body-parser", "name": "body-parser",
"description": "Node.js body parsing middleware", "description": "Node.js body parsing middleware",
"version": "1.20.1", "version": "1.20.2",
"contributors": [ "contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>", "Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)" "Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
"repository": "expressjs/body-parser", "repository": "expressjs/body-parser",
"dependencies": { "dependencies": {
"bytes": "3.1.2", "bytes": "3.1.2",
"content-type": "~1.0.4", "content-type": "~1.0.5",
"debug": "2.6.9", "debug": "2.6.9",
"depd": "2.0.0", "depd": "2.0.0",
"destroy": "1.2.0", "destroy": "1.2.0",
...@@ -18,23 +18,23 @@ ...@@ -18,23 +18,23 @@
"iconv-lite": "0.4.24", "iconv-lite": "0.4.24",
"on-finished": "2.4.1", "on-finished": "2.4.1",
"qs": "6.11.0", "qs": "6.11.0",
"raw-body": "2.5.1", "raw-body": "2.5.2",
"type-is": "~1.6.18", "type-is": "~1.6.18",
"unpipe": "1.0.0" "unpipe": "1.0.0"
}, },
"devDependencies": { "devDependencies": {
"eslint": "8.24.0", "eslint": "8.34.0",
"eslint-config-standard": "14.1.1", "eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.26.0", "eslint-plugin-import": "2.27.5",
"eslint-plugin-markdown": "3.0.0", "eslint-plugin-markdown": "3.0.0",
"eslint-plugin-node": "11.1.0", "eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "6.0.1", "eslint-plugin-promise": "6.1.1",
"eslint-plugin-standard": "4.1.0", "eslint-plugin-standard": "4.1.0",
"methods": "1.1.2", "methods": "1.1.2",
"mocha": "10.0.0", "mocha": "10.2.0",
"nyc": "15.1.0", "nyc": "15.1.0",
"safe-buffer": "5.2.1", "safe-buffer": "5.2.1",
"supertest": "6.3.0" "supertest": "6.3.3"
}, },
"files": [ "files": [
"lib/", "lib/",
......
...@@ -15,7 +15,6 @@ const Schema = require('./schema'); ...@@ -15,7 +15,6 @@ const Schema = require('./schema');
const StrictModeError = require('./error/strict'); const StrictModeError = require('./error/strict');
const ValidationError = require('./error/validation'); const ValidationError = require('./error/validation');
const ValidatorError = require('./error/validator'); const ValidatorError = require('./error/validator');
const VirtualType = require('./virtualtype');
const $__hasIncludedChildren = require('./helpers/projection/hasIncludedChildren'); const $__hasIncludedChildren = require('./helpers/projection/hasIncludedChildren');
const applyDefaults = require('./helpers/document/applyDefaults'); const applyDefaults = require('./helpers/document/applyDefaults');
const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths'); const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');
...@@ -722,6 +721,9 @@ Document.prototype.$__init = function(doc, opts) { ...@@ -722,6 +721,9 @@ Document.prototype.$__init = function(doc, opts) {
function init(self, obj, doc, opts, prefix) { function init(self, obj, doc, opts, prefix) {
prefix = prefix || ''; prefix = prefix || '';
if (obj.$__ != null) {
obj = obj._doc;
}
const keys = Object.keys(obj); const keys = Object.keys(obj);
const len = keys.length; const len = keys.length;
let schemaType; let schemaType;
...@@ -1806,28 +1808,47 @@ Document.prototype.$__setValue = function(path, val) { ...@@ -1806,28 +1808,47 @@ Document.prototype.$__setValue = function(path, val) {
Document.prototype.get = function(path, type, options) { Document.prototype.get = function(path, type, options) {
let adhoc; let adhoc;
options = options || {}; if (options == null) {
options = {};
}
if (type) { if (type) {
adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options); adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options);
} }
const noDottedPath = options.noDottedPath;
let schema = this.$__path(path); // Fast path if we know we're just accessing top-level path on the document:
// just get the schema path, avoid `$__path()` because that does string manipulation
let schema = noDottedPath ? this.$__schema.paths[path] : this.$__path(path);
if (schema == null) { if (schema == null) {
schema = this.$__schema.virtualpath(path); schema = this.$__schema.virtualpath(path);
if (schema != null) {
return schema.applyGetters(void 0, this);
}
} }
if (schema instanceof MixedSchema) {
if (noDottedPath) {
let obj = this._doc[path];
if (adhoc) {
obj = adhoc.cast(obj);
}
if (schema != null && options.getters !== false) {
return schema.applyGetters(obj, this);
}
return obj;
}
if (schema != null && schema.instance === 'Mixed') {
const virtual = this.$__schema.virtualpath(path); const virtual = this.$__schema.virtualpath(path);
if (virtual != null) { if (virtual != null) {
schema = virtual; schema = virtual;
} }
} }
const pieces = path.indexOf('.') === -1 ? [path] : path.split('.');
let obj = this._doc;
if (schema instanceof VirtualType) { const hasDot = path.indexOf('.') !== -1;
return schema.applyGetters(void 0, this); let obj = this._doc;
}
const pieces = hasDot ? path.split('.') : [path];
// Might need to change path for top-level alias // Might need to change path for top-level alias
if (typeof this.$__schema.aliases[pieces[0]] === 'string') { if (typeof this.$__schema.aliases[pieces[0]] === 'string') {
pieces[0] = this.$__schema.aliases[pieces[0]]; pieces[0] = this.$__schema.aliases[pieces[0]];
......
...@@ -25,6 +25,10 @@ const _isEmptyOptions = Object.freeze({ ...@@ -25,6 +25,10 @@ const _isEmptyOptions = Object.freeze({
transform: false transform: false
}); });
const noDottedPathGetOptions = Object.freeze({
noDottedPath: true
});
/** /**
* Compiles schemas. * Compiles schemas.
* @param {Object} tree * @param {Object} tree
...@@ -65,6 +69,7 @@ function defineKey({ prop, subprops, prototype, prefix, options }) { ...@@ -65,6 +69,7 @@ function defineKey({ prop, subprops, prototype, prefix, options }) {
Document = Document || require('../../document'); Document = Document || require('../../document');
const path = (prefix ? prefix + '.' : '') + prop; const path = (prefix ? prefix + '.' : '') + prop;
prefix = prefix || ''; prefix = prefix || '';
const useGetOptions = prefix ? Object.freeze({}) : noDottedPathGetOptions;
if (subprops) { if (subprops) {
Object.defineProperty(prototype, prop, { Object.defineProperty(prototype, prop, {
...@@ -189,7 +194,12 @@ function defineKey({ prop, subprops, prototype, prefix, options }) { ...@@ -189,7 +194,12 @@ function defineKey({ prop, subprops, prototype, prefix, options }) {
enumerable: true, enumerable: true,
configurable: true, configurable: true,
get: function() { get: function() {
return this[getSymbol].call(this.$__[scopeSymbol] || this, path); return this[getSymbol].call(
this.$__[scopeSymbol] || this,
path,
null,
useGetOptions
);
}, },
set: function(v) { set: function(v) {
this.$set.call(this.$__[scopeSymbol] || this, path, v); this.$set.call(this.$__[scopeSymbol] || this, path, v);
......
...@@ -1312,7 +1312,7 @@ Model.init = function init() { ...@@ -1312,7 +1312,7 @@ Model.init = function init() {
if (!autoCreate) { if (!autoCreate) {
return; return;
} }
return await this.createCollection({}); return await this.createCollection();
}; };
this.$init = _createCollection().then(() => _ensureIndexes()); this.$init = _createCollection().then(() => _ensureIndexes());
...@@ -3314,25 +3314,78 @@ Model.bulkWrite = async function bulkWrite(ops, options) { ...@@ -3314,25 +3314,78 @@ Model.bulkWrite = async function bulkWrite(ops, options) {
throw new MongooseError('Model.bulkWrite() no longer accepts a callback'); throw new MongooseError('Model.bulkWrite() no longer accepts a callback');
} }
options = options || {}; options = options || {};
const ordered = options.ordered == null ? true : options.ordered;
const validations = ops.map(op => castBulkWrite(this, op, options)); const validations = ops.map(op => castBulkWrite(this, op, options));
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
each(validations, (fn, cb) => fn(cb), error => { if (ordered) {
if (error) { each(validations, (fn, cb) => fn(cb), error => {
return reject(error); if (error) {
} return reject(error);
}
if (ops.length === 0) { if (ops.length === 0) {
return resolve(getDefaultBulkwriteResult()); return resolve(getDefaultBulkwriteResult());
} }
try { try {
this.$__collection.bulkWrite(ops, options).then(resolve, reject); this.$__collection.bulkWrite(ops, options, (error, res) => {
} catch (err) { if (error) {
return reject(err); return reject(error);
} }
});
resolve(res);
});
} catch (err) {
return reject(err);
}
});
return;
}
let remaining = validations.length;
let validOps = [];
let validationErrors = [];
for (let i = 0; i < validations.length; ++i) {
validations[i]((err) => {
if (err == null) {
validOps.push(i);
} else {
validationErrors.push({ index: i, error: err });
}
if (--remaining <= 0) {
completeUnorderedValidation.call(this);
}
});
}
validationErrors = validationErrors.
sort((v1, v2) => v1.index - v2.index).
map(v => v.error);
function completeUnorderedValidation() {
validOps = validOps.sort().map(index => ops[index]);
this.$__collection.bulkWrite(validOps, options, (error, res) => {
if (error) {
if (validationErrors.length > 0) {
error.mongoose = error.mongoose || {};
error.mongoose.validationErrors = validationErrors;
}
return reject(error);
}
if (validationErrors.length > 0) {
res.mongoose = res.mongoose || {};
res.mongoose.validationErrors = validationErrors;
}
resolve(res);
});
}
}); });
}; };
......
...@@ -3208,6 +3208,8 @@ Query.prototype.findOneAndUpdate = function(criteria, doc, options) { ...@@ -3208,6 +3208,8 @@ Query.prototype.findOneAndUpdate = function(criteria, doc, options) {
Query.prototype._findOneAndUpdate = async function _findOneAndUpdate() { Query.prototype._findOneAndUpdate = async function _findOneAndUpdate() {
this._castConditions(); this._castConditions();
_castArrayFilters(this);
if (this.error()) { if (this.error()) {
throw this.error(); throw this.error();
} }
...@@ -4294,6 +4296,13 @@ Query.prototype.exec = async function exec(op) { ...@@ -4294,6 +4296,13 @@ Query.prototype.exec = async function exec(op) {
return; return;
} }
if (this.options && this.options.sort) {
const keys = Object.keys(this.options.sort);
if (keys.includes('')) {
throw new Error('Invalid field "" passed to sort()');
}
}
let thunk = '_' + this.op; let thunk = '_' + this.op;
if (this.op === 'distinct') { if (this.op === 'distinct') {
thunk = '__distinct'; thunk = '__distinct';
......
...@@ -962,9 +962,9 @@ reserved.collection = 1; ...@@ -962,9 +962,9 @@ reserved.collection = 1;
*/ */
Schema.prototype.path = function(path, obj) { Schema.prototype.path = function(path, obj) {
// Convert to '.$' to check subpaths re: gh-6405
const cleanPath = _pathToPositionalSyntax(path);
if (obj === undefined) { if (obj === undefined) {
// Convert to '.$' to check subpaths re: gh-6405
const cleanPath = _pathToPositionalSyntax(path);
let schematype = _getPath(this, path, cleanPath); let schematype = _getPath(this, path, cleanPath);
if (schematype != null) { if (schematype != null) {
return schematype; return schematype;
...@@ -2357,6 +2357,11 @@ Schema.prototype.removeVirtual = function(path) { ...@@ -2357,6 +2357,11 @@ Schema.prototype.removeVirtual = function(path) {
for (const virtual of path) { for (const virtual of path) {
delete this.paths[virtual]; delete this.paths[virtual];
delete this.virtuals[virtual]; delete this.virtuals[virtual];
if (virtual.indexOf('.') !== -1) {
mpath.unset(virtual, this.tree);
} else {
delete this.tree[virtual];
}
} }
} }
return this; return this;
......
...@@ -452,7 +452,7 @@ SchemaArray.prototype.$toObject = SchemaArray.prototype.toObject; ...@@ -452,7 +452,7 @@ SchemaArray.prototype.$toObject = SchemaArray.prototype.toObject;
* ignore * ignore
*/ */
SchemaArray.prototype.discriminator = function(name, schema) { SchemaArray.prototype.discriminator = function(...args) {
let arr = this; let arr = this;
while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) {
arr = arr.casterConstructor; arr = arr.casterConstructor;
...@@ -461,7 +461,7 @@ SchemaArray.prototype.discriminator = function(name, schema) { ...@@ -461,7 +461,7 @@ SchemaArray.prototype.discriminator = function(name, schema) {
'a document array, ' + this.path + ' is a plain array'); 'a document array, ' + this.path + ' is a plain array');
} }
} }
return arr.discriminator(name, schema); return arr.discriminator(...args);
}; };
/*! /*!
......
{ {
"name": "mongoose", "name": "mongoose",
"description": "Mongoose MongoDB ODM", "description": "Mongoose MongoDB ODM",
"version": "7.0.3", "version": "7.0.4",
"author": "Guillermo Rauch <guillermo@learnboost.com>", "author": "Guillermo Rauch <guillermo@learnboost.com>",
"keywords": [ "keywords": [
"mongodb", "mongodb",
...@@ -28,10 +28,10 @@ ...@@ -28,10 +28,10 @@
"sift": "16.0.1" "sift": "16.0.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "7.21.0", "@babel/core": "7.21.4",
"@babel/preset-env": "7.20.2", "@babel/preset-env": "7.21.4",
"@typescript-eslint/eslint-plugin": "5.54.0", "@typescript-eslint/eslint-plugin": "5.57.0",
"@typescript-eslint/parser": "5.54.0", "@typescript-eslint/parser": "5.57.0",
"acquit": "1.3.0", "acquit": "1.3.0",
"acquit-ignore": "0.2.1", "acquit-ignore": "0.2.1",
"acquit-require": "0.1.1", "acquit-require": "0.1.1",
...@@ -45,28 +45,29 @@ ...@@ -45,28 +45,29 @@
"crypto-browserify": "3.12.0", "crypto-browserify": "3.12.0",
"dotenv": "16.0.3", "dotenv": "16.0.3",
"dox": "1.0.0", "dox": "1.0.0",
"eslint": "8.35.0", "eslint": "8.37.0",
"eslint-plugin-markdown": "^3.0.0", "eslint-plugin-markdown": "^3.0.0",
"eslint-plugin-mocha-no-only": "1.1.1", "eslint-plugin-mocha-no-only": "1.1.1",
"express": "^4.18.1", "express": "^4.18.1",
"highlight.js": "11.7.0", "highlight.js": "11.7.0",
"lodash.isequal": "4.5.0", "lodash.isequal": "4.5.0",
"lodash.isequalwith": "4.4.0", "lodash.isequalwith": "4.4.0",
"marked": "4.2.12", "marked": "4.3.0",
"mkdirp": "^2.1.3", "mkdirp": "^2.1.3",
"mocha": "10.2.0", "mocha": "10.2.0",
"moment": "2.x", "moment": "2.x",
"mongodb-memory-server": "8.11.5", "mongodb-memory-server": "8.12.1",
"ncp": "^2.0.0", "ncp": "^2.0.0",
"nyc": "15.1.0", "nyc": "15.1.0",
"pug": "3.0.2", "pug": "3.0.2",
"q": "1.5.1", "q": "1.5.1",
"sinon": "15.0.1", "sinon": "15.0.3",
"stream-browserify": "3.0.0", "stream-browserify": "3.0.0",
"tsd": "0.25.0", "tsd": "0.25.0",
"typescript": "4.9.5", "typescript": "5.0.3",
"uuid": "9.0.0", "uuid": "9.0.0",
"webpack": "5.75.0" "webpack": "5.77.0",
"fs-extra": "~11.1.1"
}, },
"directories": { "directories": {
"lib": "./lib/mongoose" "lib": "./lib/mongoose"
......
...@@ -10,7 +10,7 @@ try { ...@@ -10,7 +10,7 @@ try {
} }
} }
const cheerio = require('cheerio'); const cheerio = require('cheerio');
const filemap = require('../docs/source'); const docsFilemap = require('../docs/source');
const fs = require('fs'); const fs = require('fs');
const pug = require('pug'); const pug = require('pug');
const mongoose = require('../'); const mongoose = require('../');
...@@ -38,27 +38,22 @@ const Content = mongoose.model('Content', contentSchema, 'Content'); ...@@ -38,27 +38,22 @@ const Content = mongoose.model('Content', contentSchema, 'Content');
const contents = []; const contents = [];
const api = require('../docs/source/api'); for (const [filename, file] of Object.entries(docsFilemap.fileMap)) {
if (file.api) {
// API docs are special, because they are not added to the file-map individually currently and use different properties for (const prop of file.props) {
for (const _class of api.docs) { const content = new Content({
for (const prop of _class.props) { title: `API: ${prop.name}`,
const content = new Content({ body: prop.description,
title: `API: ${prop.name}`, url: `${filename}#${prop.anchorId}`
body: prop.description, });
url: `api/${_class.fileName}.html#${prop.anchorId}` const err = content.validateSync();
}); if (err != null) {
const err = content.validateSync(); console.error(content);
if (err != null) { throw err;
console.error(content); }
throw err; contents.push(content);
} }
contents.push(content); } else if (file.markdown) {
}
}
for (const [filename, file] of Object.entries(filemap)) {
if (file.markdown) {
let text = fs.readFileSync(filename, 'utf8'); let text = fs.readFileSync(filename, 'utf8');
text = markdown.parse(text); text = markdown.parse(text);
......