myModel.find({}, function(err, items){
console.log(items.length); // big number
});
Run Code Online (Sandbox Code Playgroud)
如何将返回的项目限制为仅插入的最新10项?
mar*_*rni 171
在最新的mongoose中(写作时为3.8.1),你做两件事的方式不同:(1)你必须将单个参数传递给sort(),它必须是一个约束数组或只有一个约束,并且(2) )execFind()消失了,取而代之的是exec().因此,使用mongoose 3.8.1你会这样做:
var q = models.Post.find({published: true}).sort({'date': -1}).limit(20);
q.exec(function(err, posts) {
// `posts` will be of length 20
});
Run Code Online (Sandbox Code Playgroud)
或者你可以像这样将它链接在一起:
models.Post
.find({published: true})
.sort({'date': -1})
.limit(20)
.exec(function(err, posts) {
// `posts` will be of length 20
});
Run Code Online (Sandbox Code Playgroud)
kcb*_*ner 19
像这样,使用.limit():
var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
// `posts` will be of length 20
});
Run Code Online (Sandbox Code Playgroud)
我有点懒,所以我喜欢简单的事情:
let users = await Users.find({}, null,{limit: 50});
Run Code Online (Sandbox Code Playgroud)
小智 6
models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
// `posts` with sorted length of 20
});
Run Code Online (Sandbox Code Playgroud)
查找参数
\n\nfind函数的参数如下:
\n\n\xc2\xabObject\xc2\xbb。\xc2\xabObject|String\xc2\xbb要返回的可选字段,请参阅Query.prototype.select()\xc2\xabObject\xc2\xbb可选参见Query.prototype.setOptions()\xc2\xabFunction\xc2\xbb如何限制
\n\nconst Post = require(\'./models/Post\');\n\nPost.find(\n { published: true }, \n null, \n { sort: { \'date\': \'asc\' }, limit: 20 },\n function(error, posts) {\n if (error) return `${error} while finding from post collection`;\n\n return posts; // posts with sorted length of 20\n }\n);\nRun Code Online (Sandbox Code Playgroud)\n\n额外信息
\n\nMongoose 允许您以不同的方式查询您的集合,例如:\n官方文档
\n\n// named john and at least 18\nMyModel.find({ name: \'john\', age: { $gte: 18 }});\n\n// executes, passing results to callback\nMyModel.find({ name: \'john\', age: { $gte: 18 }}, function (err, docs) {});\n\n// executes, name LIKE john and only selecting the "name" and "friends" fields\nMyModel.find({ name: /john/i }, \'name friends\', function (err, docs) { })\n\n// passing options\nMyModel.find({ name: /john/i }, null, { skip: 10 })\n\n// passing options and executes\nMyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});\n\n// executing a query explicitly\nvar query = MyModel.find({ name: /john/i }, null, { skip: 10 })\nquery.exec(function (err, docs) {});\n\n// using the promise returned from executing a query\nvar query = MyModel.find({ name: /john/i }, null, { skip: 10 });\nvar promise = query.exec();\npromise.addBack(function (err, docs) {});\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
98220 次 |
| 最近记录: |