提问人:Saif eldeen Adel 提问时间:8/26/2021 更新时间:8/26/2021 访问量:543
Mongoose 查询未运行 - “cursor.toArray is not a function”
Mongoose query not running - "cursor.toArray is not a function"
问:
MongoDB 初学者,无法使查询正常工作。正在遵循各种教程,它是一个演示笔记应用程序。他们保存新笔记的语法工作正常。
但是,在打印注释列表时,给我的语法似乎有问题,或者我做错了什么。
const mongoose = require("mongoose");
const url =
"mongodb+srv://Saif:<password>@cluster0.8d2lb.mongodb.net/notes-app?retryWrites=true&w=majority";
mongoose.connect(url, {
useNewUrlParser: true,
});
const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean,
});
const Note = mongoose.model("Note", noteSchema);
Note.find({}).then((result) => {
result.forEach((note) => {
console.log(note);
});
mongoose.connection.close();
});
查找文档后,实际语法略有不同,他们传入回调而不是使用 promise。但是将该块更改为使用回调仍然不起作用find
Note.find({}, (error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})
错误
TypeError: cursor.toArray is not a function
at model.Query.<anonymous> (D:\Folders\Documents\CS.........
(Use `node --trace-warnings ...` to show where the warning was created)
(node:27108) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:27108) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
答:
0赞
Swapnil Soni
8/26/2021
#1
.find
model 中的方法返回 Query 对象而不是 Cursor
对于游标,您需要执行.exec
Note.find({}).exec((error, data) => {
if (error) {
console.log(error);
} else {
data.forEach((note) => {
console.log(note);
})
}
mongoose.connection.close()
})
评论
0赞
Saif eldeen Adel
8/26/2021
仍然返回相同的游标错误。我什至不知道光标是什么。什么时候需要查询对象,什么时候需要游标?为什么你的例子不起作用
0赞
Saif eldeen Adel
8/26/2021
事实证明,在 Mongoose 6.0 版上存在一些与此相关的问题,所以我刚刚安装了 v5.13.8 版本,我的示例工作正常
0赞
Swapnil Soni
8/26/2021
好的,您可以尝试在 Mongoose 上创建问题并让他们知道错误:)OSS贡献,你知道的!
评论