몽구스에서는 날짜별로 어떻게 정렬하나요?(node.disples)
Mongoose에서 다음 쿼리를 실행한다고 가정해 보겠습니다.
Room.find({}, (err,docs) => {
}).sort({date:-1});
이거 안 돼!
Mongoose에서의 정렬은 릴리스에 따라 진화하여 이러한 답변 중 일부는 더 이상 유효하지 않습니다.Mongoose의 4.1.x 릴리스에서는, 이 릴리스의 내림차순 정렬은date필드는 다음 중 하나의 방법으로 실행할 수 있습니다.
Room.find({}).sort('-date').exec((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });
오름차순 정렬의 경우-문자열 버전의 접두사 또는 값 사용1,asc, 또는ascending.
정답은 다음과 같습니다.
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
오늘 Mongoose 3.5(.2)를 사용하여 이 문제를 처리했는데, 어떤 답변도 이 문제를 해결하는 데 도움이 되지 않았습니다.다음 코드 스니펫이 문제를 해결합니다.
Post.find().sort('-posted').find(function (err, posts) {
// user posts array
});
필요한 모든 표준 파라미터를 전송할 수 있습니다.find()(예: 구 및 반환 필드) 단, 콜백은 없습니다.콜백이 없으면 체인으로 연결된 Query 개체를 반환합니다.sort()켜세요. 전화 주세요.find()(더 많은 파라미터의 유무에 관계없이 효율상의 이유로 아무것도 필요 없습니다) 콜백에 결과 세트를 취득할 수 있습니다.
Post.find().sort({date:-1}, function(err, posts){
});
동작도 할 수 있습니다.
편집:
에러가 발생했을 경우는, 이것을 사용해 주세요.sort() only takes 1 Argument:
Post.find({}, {
'_id': 0, // select keys to return here
}, {sort: '-date'}, function(err, posts) {
// use it here
});
저는 이렇게 합니다.
Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
...
})
이것은 가장 최근의 것을 먼저 보여줍니다.
여기 있는 모든 anwers는 사실 맞습니다만, 모델에 '-date'라는 필드가 없거나 모델을 작성할 때 옵션: timestamps: true in options를 통과했을 경우, 때때로 '-date' 또는 '-1'을 쓸 수 없다는 것을 명확히 하기 위해 anwser를 씁니다.타임스탬프: true를 사용하는 경우 sort({createdAt: -1})를 입력해야 합니다.그러면 됩니다.
이것이 도움이 되는지 확인하세요> mongoose 정렬 방법
> http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order도 참조해 주세요.
쇼트 솔루션:
const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }
Room.find(query, projection, options).exec(function(err, docs) { ... });
를 기준으로 정렬할 수도 있습니다._id예를 들어, 가장 최근의 기록을 얻으려면 다음과 같이 할 수 있습니다.
const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });
그게 훨씬 더 빠르죠, 왜냐면 전 기꺼이 당신네 집들이date필드가 색인화되지 않았습니다.
난 이게 좋아.
`Post.find().sort({postedon: -1}).find(function (err, sortedposts){
if (err)
return res.status(500).send({ message: "No Posts." });
res.status(200).send({sortedposts : sortedposts});
});`
ES6 솔루션과 Koa.
async recent() {
data = await ReadSchema.find({}, { sort: 'created_at' });
ctx.body = data;
}
언급URL : https://stackoverflow.com/questions/5825520/in-mongoose-how-do-i-sort-by-date-node-js
'programing' 카테고리의 다른 글
| JSON 구문 분석 오류 예기치 않은 입력 끝 (0) | 2023.04.01 |
|---|---|
| AngularJS - ng-repeat을 사용하여 무선 입력 세트 생성 (0) | 2023.04.01 |
| 스토어드 프로시저를 호출하기 위한 Spring JDBC 템플릿 (0) | 2023.04.01 |
| AngularJS: 애플리케이션을 Angular 앱에 중첩하는 방법 (0) | 2023.04.01 |
| query_cache_type: 활성화 또는 비활성화? (0) | 2023.04.01 |