MongoDB文档Model.find()中的歧义



所以我正在做本教程,并在步骤5。创建通过Restful API访问书籍数据的路线它说

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Book = require('../models/Book.js');
/* GET ALL BOOKS */
router.get('/', function(req, res, next) {
Book.find(function (err, products) {//this is the line I'm having trouble understanding
if (err) return next(err);
res.json(products);
});
});

我不明白的是,如果我正确阅读了Mongoose.find((文档,那么在传递回调函数之前,至少需要传递一个"options"的强制参数。这似乎跳过了强制参数。

教程是否与文档不一致?

我尝试过的:

审阅文档@https://github.com/Automattic/mongoose/blob/master/History.md

但这并没有提到第一个第一个参数的可选性。

Mongoose从Book.find()构建了一个MongoDB.find()查询,如果您查看Mongoose源代码,您会发现Model.find会检查find的第一个参数是否是函数,如果是,则在第1566行将该函数作为MongoDB查询构建器的回调传递。

这样,Mongoose将一个空的conditions对象与回调一起传递给MongoDBfind函数,回调将返回您案例中的所有书籍。

[options]是可选的,因此不强制传递,但是文档中的语句The conditions are cast to their respective SchemaTypes before the command is sent.看起来与实际的.find()函数不一致。

Model.find()

Parameters

conditions «Object»

要返回的[projection] «Object|String»可选字段,请参阅Query.prototype.select()

[options] «Object»可选,请参阅Query.protype.setOptions((

[callback] «Function»退货:«查询»查找文档

在发送命令之前,条件将强制转换为各自的SchemaTypes。

有关更深入的信息,您可以查看源代码。

首先检查.find()函数的每个参数是否是函数(typeof parameter=== 'function')

最新更新