Query.prototype.hint() 如何在Mongoose中工作?
Query.prototype.hint()函数用于设置查询提示。提示对象作为参数传递给此函数。
句法:
Query.prototype.hint()
参数:此函数有一个参数val ,它是一个提示对象。
返回值:此函数返回查询对象。
Mongoose安装:
npm install mongoose
安装mongoose模块后,您可以使用命令在命令提示符下检查您的mongoose版本。
npm mongoose --version
数据库:这里使用的示例数据库如下所示:
示例 1:
index.js
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
var query = User.find();
query.hint({index:1})
console.log("Hint:", query.options)
index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express()
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
var query = User.find();
query.hint({index: -1})
console.log("Hint:", query.options)
app.listen(3000, function(error ) {
if(error) console.log(error)
console.log("Server listening on PORT 3000")
});
项目结构将如下所示:
使用以下命令运行index.js文件:
node index.js
输出:
Hint: { hint: { index: 1 } }
示例 2:
index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express()
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
var query = User.find();
query.hint({index: -1})
console.log("Hint:", query.options)
app.listen(3000, function(error ) {
if(error) console.log(error)
console.log("Server listening on PORT 3000")
});
使用以下命令运行index.js文件:
node index.js
输出:
Server listening on PORT 3000
Hint: { hint: { index: -1 } }
参考: https://mongoosejs.com/docs/api/query.html#query_Query-hint