【问题标题】:Cannot log mongoose model attributes无法记录猫鼬模型属性
【发布时间】:2021-10-27 18:11:01
【问题描述】:

这是我的猫鼬模型的问题。在底部查找代码

下面粘贴的是我使用 mongoose 与 MongoDB 交互的 node.js 代码。出于某种原因,当我运行它时,我得到以下结果:

    Starting...
(node:7863) UnhandledPromiseRejectionWarning: MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments
    at Collection.find (/Users/justing/Documents/WebDev/FruitsProject/node_modules/mongodb/lib/collection.js:238:19)
    at NativeCollection.<computed> [as find] (/Users/justing/Documents/WebDev/FruitsProject/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:191:33)
    at NativeCollection.Collection.doQueue (/Users/justing/Documents/WebDev/FruitsProject/node_modules/mongoose/lib/collection.js:135:23)
    at /Users/justing/Documents/WebDev/FruitsProject/node_modules/mongoose/lib/collection.js:82:24
    at processTicksAndRejections (internal/process/task_queues.js:77:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7863) 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:7863) [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.

我应该看到的是 Fruit 模型实例的 name 属性。根据文档,我尝试用 {} 替换参数 #1,但我似乎无法获得所需的结果,这只是为了 console.log 他们。

const mongoose = require("mongoose");
console.log("Starting...");
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser:true});

const fruitSchema = new mongoose.Schema({
  name: String,
  rating: Number,
  review: String
});

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

const fruit = new Fruit ({
  name: "Apple",
  rating: 7,
  review: "Pretty solid as a fruit."
});

fruit.save();

 Fruit.find({},function(err,fruits){
   if (err) {
     console.log(err);
   } else {
     console.log(fruits);
     fruits.forEach(function(fruit){
       console.log(fruit.name);
     });
   }
  });

【问题讨论】:

  • 尝试在Fruit.find 之前添加一个await 关键字,其中很多方法都会返回一个promise。

标签: javascript node.js mongodb mongoose callback


【解决方案1】:

我认为你的代码没有错误,但如果这段代码运行多次,你应该在另一个文件中定义你的 Fruit Schema,因为你不能在运行时重新定义相同的模式。

【讨论】:

  • @JuanHuandred 就像他说的,在一个文件中有一个模式并在另一个文件中需要它是非常常见的。
猜你喜欢
  • 2021-10-01
  • 2013-02-11
  • 1970-01-01
  • 2020-06-29
  • 2016-06-29
  • 2022-10-24
  • 1970-01-01
  • 2012-12-27
  • 2012-01-14
相关资源
最近更新 更多