Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

node.js - How do I sort documents by Mongo based on one criterion?

I have the following model in Mongoose

Store:{
    name: <String>,
    regionName: <String>,
    coordinates: CoordinatesSchema
    }

CoordinatesSchema :{
longitude: <Number>
latitude: <Number>
}

I want to search the database by giving my own coordinates (mylatitude, my longitude) for the 4 nearest stores, sorting them from the nearest to the farthest (the distance is considered to be the Cartesian distance of two points-sqrt((mylongitude-longtude)^2 +(mylatitude-latitude)^2). Is there a way to place an auxiliary function in the model so that it is returns to me the documents with a command like Store.find({something}) or do I have to take all documents of the database and do it with a function outside?

question from:https://stackoverflow.com/questions/66048799/how-do-i-sort-documents-by-mongo-based-on-one-criterion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to docs you can sort in this way

yourModel.find({}).sort('yourSort').then(result => {console.log(result)})

You can use multiple ways. As explained into docs, for example sort({ field: 'asc', test: -1 }) is the same as sort('field -test')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...