Model.find() 不再在 Mongoose 中接受回调函数。

huangapple go评论135阅读模式
英文:

Model.find() no longer accepts a callback in Mongoose

问题

I am currently learning Mongoose from Dr. Angela Yu's Course, however since mongoose has changed the syntax of find and other several functions, it is throwing above error

Here is the JavaScript Code

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
var items = [];

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect("mongodb://localhost:27017/todoList", {useNewUrlParser: true});

const ItemSchema = new mongoose.Schema({
 name: String
});

const Item = mongoose.model("Item", ItemSchema); // Items = collection name & ItemScema = Schema

// const <constantName> = new <ModelName> ({
//     <fieldName> : <fieldData>
//         })

//Some Default Items for the list
const Item1 = new Item({
    name: "Welcome To Your To-Do-List!"
})

const Item2 = new Item({
    name: "Hit the + button to add a new Item"
})

const Item3 = new Item({
    name: "<-- Hit this to delete an item"
})

const defaultItems = [Item1, Item2, Item3];

app.get("/", function (req, res) {

    var today = new Date();

    var options = { weekday: "long", day: "numeric", year: "numeric" , month: "numeric" };

    var day = today.toLocaleDateString("en-GB", options);

   Item.find({}, function(err, FoundItems){
    console.log(FoundItems);
    res.render("list", {kindOfDay: day, newItem: FoundItems});

   })
});
app.post("/", function(req, res){
    var item = req.body.newItem;

    items.push(item);

    res.redirect("/");

})
app.listen(3000, function () { //or process.env.PORT || 2000
    console.log("Server started on port 3000");
})

The EJS code is below

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To Do List </title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <h1> <%= kindOfDay%></h1> 
  <ul>
    <li>Buy Food</li>
    <li>Cook Food</li>
    <li>Eat Food</li>
    <!--<li><%= newItem %></li>  -->
    <%for (var i = 0; i < newItem.length; i++){ %>
        <li><%= newItem[i] %></li>
   <% }  %>
 
  </ul>

  <form class="" action = "/" method = "post">
    <input type = "text" name = "newItem">
    <button type = "submit" name = "button">Add</button>
  </form>
    </body>
</html>

This is a to-do-list app and hence I need to render all the list items to my To-do-list. I have been trying to learn the alternatives but since I am a newbie I am unable to find a solution.

英文:

I am currently learning Mongoose from Dr. Angela Yu's Course , however since mongoose has changed the syntax of find and other several functions, it is throwing above error

Here is the JavaScript Code

const express = require(&quot;express&quot;);
const bodyParser = require(&quot;body-parser&quot;);
const mongoose = require(&quot;mongoose&quot;);
const app = express();
var items = [];
app.set(&quot;view engine&quot;, &quot;ejs&quot;);
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect(&quot;mongodb://localhost:27017/todoList&quot;, {useNewUrlParser: true});
const ItemSchema = new mongoose.Schema({
name: String
});
const Item = mongoose.model(&quot;Item&quot;, ItemSchema); // Items = collection name &amp; ItemScema = Schema
// const &lt;constantName&gt; = new &lt;ModelName&gt; ({
//     &lt;fieldName&gt; : &lt;fieldData&gt;
//         })
//Some Default Items for the list
const Item1 = new Item({
name: &quot;Welcome To Your To-Do-List!&quot;
})
const Item2 = new Item({
name: &quot;Hit the + button to add a new Item&quot;
})
const Item3 = new Item({
name: &quot;&lt;-- Hit this to delete an item&quot;
})
const defaultItems = [Item1, Item2, Item3];
// Item.find(AllItems){
//     .then(function(){
//         console.log(&quot;Here are the items&quot;);
//     }) 
//     .catch(function(err){
//         console.log(err);
//     })
// };
// Item.deleteMany( {name:&quot;&lt;-- Hit this to delete an item&quot;})
//  .then(function(){
//     console.log(&quot;Deleted&quot;)
//  })
//  .catch(function(err){
//     console.log(err);
// })
// Item.insertMany(defaultItems)
//       .then(function () {
//         console.log(&quot;Successfully saved defult items to DB&quot;);
//       })
//       .catch(function (err) {
//         console.log(err);
//       });
app.get(&quot;/&quot;, function (req, res) {
var today = new Date();
var options = { weekday: &quot;long&quot;, day: &quot;numeric&quot;, year: &quot;numeric&quot; , month: &quot;numeric&quot; };
var day = today.toLocaleDateString(&quot;en-GB&quot;, options);
Item.find({}, function(err, FoundItems){
console.log(FoundItems);
res.render(&quot;list&quot;, {kindOfDay: day, newItem: FoundItems});
})
});
app.post(&quot;/&quot;, function(req, res){
var item = req.body.newItem;
items.push(item);
res.redirect(&quot;/&quot;);
})
app.listen(3000, function () { //or process.env.PORT || 2000
console.log(&quot;Server started on port 3000&quot;);
})

The EJS code is below

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;title&gt;To Do List &lt;/title&gt;
&lt;link rel = &quot;stylesheet&quot; href = &quot;css/styles.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt; &lt;%= kindOfDay%&gt;&lt;/h1&gt; 
&lt;ul&gt;
&lt;li&gt;Buy Food&lt;/li&gt;
&lt;li&gt;Cook Food&lt;/li&gt;
&lt;li&gt;Eat Food&lt;/li&gt;
&lt;!-- &lt;li&gt;&lt;%= newItem %&gt;&lt;/li&gt;  --&gt;
&lt;%for (var i = 0; i &lt; newItem.length; i++){ %&gt;
&lt;li&gt;&lt;%= newItem[i] %&gt;&lt;/li&gt;
&lt;% }  %&gt;
&lt;/ul&gt;
&lt;form class=&quot;&quot; action = &quot;/&quot; method = &quot;post&quot;&gt;
&lt;input type = &quot;text&quot; name = &quot;newItem&quot;&gt;
&lt;button type = &quot;submit&quot; name = &quot;button&quot;&gt;Add&lt;/button&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

This is a to-do-List app and hence I need to render all the list items to my To-do-list , I have been trying to learn the alternatives but since I am a newbie I am unable to find a solution.

答案1

得分: 3

以下是翻译的内容:

首先,我相当肯定你已经查看了文档的链接:

因为我也是新手,我无法理解为什么await MyModel.find({});不起作用,这是因为我没有在异步函数中使用它。请记住,await 必须在异步函数内部使用。

假设你已经创建了水果模式(fruit schema)和水果模型(fruit model),并像 Angela 在视频中做的那样添加了一个水果示例。

const fruitSchema = new mongoose.Schema({
  name: String,
  rating: {
    type: Number,
    min: 1,
    max: 10
  },
  review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
  name: "peach",
  rating: 10,
  review: "yummyyy"
});

假设我们只想获取水果对象的名称。这是如何做的:

async function myfruits() {
    const fruits = await Fruit.find({});
    fruits.forEach(function(fruit) {
        console.log(fruit.name);
    });
}
myfruits();

我们得到了水果数组,这是一个水果对象的数组,然后使用 forEach 我们获取了我们水果的名称。

英文:

well i had the same issue so this is how i resolve it (just in case):

first, im pretty sure you already looked but here is the link of the doc:

since i'm also a newbie i couldnt get why await MyModel.find({});
doesn't work, that's because i didnt use it in a async function. remember await need to be inside a async function

so let's say you created fruit schema and fruit model and add an example of fruit like Angela did in the videos

<!-- begin snippet: js hide: false console: false babel: false -->

<!-- language: lang-js -->

const fruitSchema = new mongoose.Schema({
name: String,
rating: {
type: Number,
min: 1,
max: 10
},
review: String
});
const Fruit = mongoose.model(&quot;Fruit&quot;, fruitSchema);
const fruit = new Fruit({
name: &quot;peach&quot;,
rating: 10,
review: &quot;yummyyy&quot;
});

<!-- end snippet -->

let's say we want to get only the name of our fruit object. that's how you do it:

<!-- begin snippet: js hide: false console: false babel: false -->

<!-- language: lang-js -->

async function myfruits() {
const fruits= await Fruit.find({});
fruits.forEach(function(fruit){
console.log(fruit.name);
});
}
myfruits();

<!-- end snippet -->

we got the fruits array which is an array of fruit objects then using foreach we got the names of our fruits

答案2

得分: 1

这应该可以工作

async function getItems(){

  const Items = await Item.find({});
  return Items;

}

app.get("/", function (req, res) {

  var today = new Date();

  var options = { weekday: "long", day: "numeric", year: "numeric" , 
  month: "numeric" };

  var day = today.toLocaleDateString("en-GB", options);

  getItems().then(function(FoundItems){
    
    res.render("list", {kindOfDay: day, newItem:FoundItems});

  });

});
英文:

This should work

async function getItems(){
const Items = await Item.find({});
return Items;
}
app.get(&quot;/&quot;, function (req, res) {
var today = new Date();
var options = { weekday: &quot;long&quot;, day: &quot;numeric&quot;, year: &quot;numeric&quot; , 
month: &quot;numeric&quot; };
var day = today.toLocaleDateString(&quot;en-GB&quot;, options);
getItems().then(function(FoundItems){
res.render(&quot;list&quot;, {kindOfDay: day, newItem:FoundItems});
});
});

答案3

得分: 1

尝试这个:

app.get("/", function (req, res) {

  var today = new Date();

  var options = { weekday: "long", day: "numeric", year: "numeric" , 
  month: "numeric" };

  var day = today.toLocaleDateString("en-GB", options);

  Item.find({}).then(function(FoundItems){
    
    res.render("list", {kindOfDay: day, newItem:FoundItems});

  })
   .catch(function(err){
    console.log(err);
  })

});
英文:

Try this:

app.get(&quot;/&quot;, function (req, res) {
var today = new Date();
var options = { weekday: &quot;long&quot;, day: &quot;numeric&quot;, year: &quot;numeric&quot; , 
month: &quot;numeric&quot; };
var day = today.toLocaleDateString(&quot;en-GB&quot;, options);
Item.find({}).then(function(FoundItems){
res.render(&quot;list&quot;, {kindOfDay: day, newItem:FoundItems});
})
.catch(function(err){
console.log(err);
})
});

答案4

得分: 1

不要将其异步化,只需添加 Model.find({}).then function(),这将解决你的问题。

英文:

Don't make it async just add Model.find({}).then function(), this will solve your problem

答案5

得分: 0

Dr. Angela Yu正在使用mongoose 5.3.4,我遇到了相同的问题,通过以下方式解决了它:npm卸载mongoose然后npm i mongoose@5.3.4

英文:

Dr. Angela Yu is using mongoose 5.3.4, i had same issue solved it by following --> npm uninstall mongoose and then npm i mongoose@5.3.4

答案6

得分: 0

将您的Mongoose版本更改为5.0,不支持6.0或更高版本。

英文:

Change your mongoose version in to 5.0 its is not support from 6.0 or upper version

答案7

得分: 0

首先使用 npm uninstall mongoose 卸载现有的 mongoose,然后使用 npm install mongoose@5.3.4 重新安装它(使用特定版本的 mongoose),然后你的工作就能正常运行。

英文:

First uninstall the existing mongoose by npm uninstall mongoose and then reinstall it by npm install mongoose@5.3.4 (using a specific version of mongoose) then your works perfectly.

答案8

得分: 0

在新版本的 Mongoose 中,Mongoose 模型提供了多个用于 CRUD 操作的静态辅助函数。这些函数中的每一个都返回一个 Mongoose 查询对象。不幸的是,这些辅助函数(例如 Model.find()、Model.insertMany()、Model.updateOne())不再接受回调函数作为参数。但它们的返回值是查询对象或 Promise 对象,我们可以使用 .then() 方法来解决这个问题。

我的解决方案如下:

app.get("/", function(req, res) {

    var today = new Date();

    var options = { weekday: "long", day: "numeric", year: "numeric" , month: "numeric" };

    var day = today.toLocaleDateString("en-GB", options);

    Item.find({}).then(foundItems => {
        console.log(foundItems);
        res.render("list", { kindOfDay: day, newItem: foundItems });

    })
    .catch(err => { console.error('there was an error', err); });
});

希望这对你有所帮助。

英文:

In the new version of mongoose, Mongoose models provide several static helper functions for CRUD operations. Each of these functions returns a mongoose Query object.
Unfortunately, these helper functions(e.g. Model.find(),Model.insertMany(),Model.updateOne()) no longer accept the callback as a parameter. But the return values of them are Query or Promise Object, we can use the .then() method to fix this issue.

My solution is as follows:

app.get(&quot;/&quot;, function(req, res) {
var today = new Date();
var options = { weekday: &quot;long&quot;, day: &quot;numeric&quot;, year: &quot;numeric&quot; , month: &quot;numeric&quot; };
var day = today.toLocaleDateString(&quot;en-GB&quot;, options);
Item.find({}).then(foundItems =&gt; {
console.log(foundItems);
res.render(&quot;list&quot;, {kindOfDay: day, newItem: FoundItems});
})
.catch(err =&gt; {console.error(&#39;there was an error&#39;, err)});
});

答案9

得分: 0

我遇到了相同的问题。在我的情况下,我试图使用 find 进行过滤:

let output = await Item.find(item => item.id === Id); //这引发了错误

所以我把它改成了:

let output = Item.find({}).then(items => {
  return items.filter(item => item.id === Id);
});

然后它就起作用了。希望这对某人有所帮助🙂

英文:

I had the same issue. In my case, I was trying to do a filter using find:

let output = await Item.find(item =&gt; item.id === Id); //this threw the error

So I changed it to:

let output = Item.find({}).then(items =&gt; {
return items.filter(item =&gt; item.id === Id);
});

And it worked. I hope this helps someone🙂

答案10

得分: 0

使用thencatch方法来处理承诺:

User.findById(id)
    .then(user => {
        done(null, user);
    })
    .catch(err => {
        done(err, null);
    });

它应该可以工作。

英文:

Use this promise method by then and catch

User.findById(id)
.then(user =&gt; {
done(null, user);
})
.catch(err =&gt; {
done(err, null);
});

It should work.

答案11

得分: 0

是的,当您使用高于6版本的Mongoose时,将会出现此消息。因此,我建议两个选项。第一个选项是降级您的Mongoose版本(这并不是最佳解决方案)。
要做到这一点,只需运行以下命令。

npm i monggose@6

第二个解决方案是使用try-catch语句。

Item.find({}).then((result) => console.log(result)).catch((err) => console.log(err))
英文:

Yep, this message will come when you are using a Mongoose version above 6. so I would suggest two options. The first one is to downgrade your Mongoose version(which is not the best solution)
to do that just run the following command.

npm i monggose@6

The second solution is to use a try-catch statement.

Item.find({}).then((result) =&gt;console.log(result)).catch((err)=&gt;console.log(err))

答案12

得分: 0

同样的问题在2023年7月21日已经被解决了。

async function logAllFruits() {
  try {
    // 从Fruit集合中获取所有文档
    const allFruits = await Fruit.find();

    // 记录所有文档的整个集合
    console.log('所有水果:', allFruits);
  } catch (error) {
    console.error('错误:', error);
  }
}

logAllFruits();
英文:

same problem got solved by This code works for me as of 7/21/2023

   async function logAllFruits() {
try {
// Fetch all documents from the Fruit collection
const allFruits = await Fruit.find();
// Log the entire collection of documents
console.log(&#39;All Fruits:&#39;, allFruits);
} catch (error) {
console.error(&#39;Error:&#39;, error);
}
}
logAllFruits();

答案13

得分: -1

请阅读这个Mongoose新版本的文档:https://mongoosejs.com/docs/api/model.html#model_Model-find

并且阅读关于'async'函数和'promises'的文档。

你寻找的答案在上述文档中,请仔细阅读,你将能够自行完成。如果你仍然遇到困难,请回复这条评论给我留言。

此外,我也正在学习MERN堆栈,与您学习相同的课程。

英文:

Here Read This Mongoose new version Documentation: https://mongoosejs.com/docs/api/model.html#model_Model-find

and Read the documentation of 'async' functions and 'promises' one too.

The answer you are looking for is in the above docs, pls read them carefully and you will be able to do it yourself. If you still struggle pls. message me by replying this comment.

Also I am also learning MERN Stack for same Course.

huangapple
  • 本文由 发表于 2023年3月7日 04:43:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定