📜  mongoose find()函数

📅  最后修改于: 2022-05-13 01:56:27.451000             🧑  作者: Mango

猫鼬 find()函数

find()函数用于从 MongoDB 数据库中查找特定数据。它有 3 个参数,它们是查询(也称为条件)、查询投影(用于提及要在查询中包含或排除哪些字段),最后一个参数是一般查询选项(如限制、跳过等) .

猫鼬模块的安装:

  1. 您可以访问安装 mongoose 模块的链接 https://www.npmjs.com/package/mongoose。您可以使用此命令安装此软件包。
    npm install mongoose
  2. 安装 mongoose 模块后,您可以使用命令在命令提示符下检查您的 mongoose 版本。
    npm version mongoose
  3. 之后,您可以创建一个文件夹并添加一个文件,例如 index.js。要运行此文件,您需要运行以下命令。
    node index.js

文件名: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 }
});
  
// Only one parameter [query/condition]
// Find all documents that matches the
// condition name='Punit'
User.find({ name: 'Punit'}, function (err, docs) {
    if (err){
        console.log(err);
    }
    else{
        console.log("First function call : ", docs);
    }
});
  
// Only Two parameters [condition, query projection]
// Here age:0 means don't include age field in result 
User.find({ name: 'Punit'}, {age:0}, function (err, docs) {
    if (err){
        console.log(err);
    }
    else{
        console.log("Second function call : ", docs);
    }
});
  
// All three parameter [condition, query projection,
// general query options]
// Fetch first two records whose age >= 10 
// Second parameter is null i.e. no projections
// Third parameter is limit:2 i.e. fetch
// only first 2 records
User.find({ age: {$gte:10}}, null, {limit:2}, function (err, docs) {
    if (err){
        console.log(err);
    }
    else{
        console.log("Third function call : ", docs);
    }
});

运行程序的步骤:

  1. 项目结构将如下所示:
    项目结构
  2. 确保您已使用以下命令安装 mongoose 模块:
    npm install mongoose
  3. 下面是执行 find()函数之前数据库中的示例数据,您可以使用任何 GUI 工具或终端查看数据库,例如我们使用 Robo3T 的 GUI 工具,如下所示:
    数据库
  4. 使用以下命令运行 index.js 文件:
    node index.js

这就是在 Node.js 和 MongoDB 中使用 mongoose find()函数的方法。