Comments (3)
TestModel.find().sort({ $natural: 1 }).sort({ creationDate: 'desc' })
will make the sort condition { $natural: 1, creationDate: -1 }
. To make sort()
overwrite the existing query sort instead of merging, use .sort({ creationDate: 'desc' }, { overwrite: true })
from mongoose.
Please modify the following script to demonstrate your issue:
const mongoose = require('mongoose');
const testSchema = new mongoose.Schema({
name: String,
age: Number
});
const Test = mongoose.model('Test', testSchema);
async function run() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
for (let i = 0; i < 11; i++) {
await Test.create({
name: `Test${i}`,
age: i
});
}
const natural = await Test.find().sort({ $natural: 1 });
console.log('This is natural', natural)
const res = await Test.find().sort({ age: -1 });
console.log('this is res', res);
}
run();
from mongoose.
@vkarpov15 actually, the way it works is fine, merging is the expected behavior for me. Btw thanks for the tips ;)
@IslandRhythms thanks for your reactivity. Here is the modified script:
const mongoose = require('mongoose');
const testSchema = new mongoose.Schema({
name: String,
age: Number
});
const Test = mongoose.model('Test', testSchema);
async function run() {
await mongoose.connect('mongodb://127.0.0.1:27017/test2');
await mongoose.connection.dropDatabase();
for (let i = 0; i < 11; i++) {
await Test.create({
name: `Test${i}`,
age: i
});
}
const promise = Test.find().sort({ $natural: 1 })
promise.sort({ age: -1 })
console.log('this is res', await promise);
}
run();
As expected, it throws the same error:
yarn run v1.22.21
$ node ./app.js
/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cmap/connection.js:281
throw new error_1.MongoServerError(document);
^
MongoServerError: $natural sort cannot be set to a value other than -1 or 1.
at Connection.sendCommand (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cmap/connection.js:281:27)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Connection.command (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cmap/connection.js:304:26)
at async Server.command (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/sdam/server.js:169:24)
at async executeOperation (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/operations/execute_operation.js:126:16)
at async FindCursor._initialize (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cursor/find_cursor.js:55:26)
at async [kInit] (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cursor/abstract_cursor.js:454:27)
at async next (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cursor/abstract_cursor.js:514:13)
at async [Symbol.asyncIterator] (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cursor/abstract_cursor.js:160:34)
at async FindCursor.toArray (/Users/garcias/DEV/00_test/mongoose/node_modules/mongodb/lib/cursor/abstract_cursor.js:273:26) {
errorResponse: {
ok: 0,
errmsg: '$natural sort cannot be set to a value other than -1 or 1.',
code: 2,
codeName: 'BadValue'
},
ok: 0,
code: 2,
codeName: 'BadValue',
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.18.2
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
from mongoose.
Related Issues (20)
- Create tool that can introspect collection and turn into mongoose Schema
- bulkWrite does not throw an error if all documents are invalid (ordered: false) HOT 4
- Accessing the .toObject() of a subdocument inside of a method raises a typing error HOT 3
- Document methods are not available when it is populated HOT 1
- StrictModeError: Path "$comment" is not in schema, strict mode is `true`, and upsert is `true` HOT 5
- Return the deleted document after a deleteOne operation HOT 2
- Describe `deleteOne` or `remove` method of Document in the doc HOT 3
- Merging of discrimintor schema "_indexes" duplicates when both 'from' and 'to' are schema instances HOT 1
- Document.toObject() does not apply to subdocuments HOT 1
- Pre validate: is not triggert on all sub documents when set via _.set() with a nested path HOT 1
- Using mongoose and got error when adding new data: Product validation failed HOT 1
- Discriminators: Return derived model when issuing Find on base model HOT 4
- When updating elements of primitive array using positional filtered operator, update value is incorrectly cast to array
- empty objects are being saved as null HOT 1
- Autoindex is recreating existing indexes HOT 3
- StrictPopulateError: Cannot populate path `totalLinksList` because it is not in your schema. Set the `strictPopulate` option to false to override. HOT 1
- Breaking types of `toObject` on SubDocument or ArraySubdocument HOT 1
- Make autoIndex syncIndex instead of createIndex HOT 6
- Using Promise.all inside transactions errors with "Cannot pin multiple connections to the same session" HOT 8
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mongoose.