【问题标题】:Failure to find mongodb array using node.js使用 node.js 找不到 mongodb 数组
【发布时间】:2020-12-17 18:25:19
【问题描述】:

我的代码成功地将 html 帖子中的内容发送到我存储帖子和数组的 mongodb 默认集合,我在尝试查找数组时遇到错误(node:23) UnhandledPromiseRejectionWarning: TypeError: Post.findOne(...).toArray is not a function。我做了研究,没有得出任何结论,也不知道如何解决它,我希望得到一些反馈,并可能显示改进代码,因为我是 web 开发的新手。

我希望脚本做的是找到帖子中的所有 cmets 并将结果输出到 console.log 或将其设为 const 以便我可以在代码中引用它,如果您需要我详细说明,请询问,谢谢。

app.js

// mongdb cloud connection is here
mongoose
  .connect("secret", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then(() => {
    console.log("connected to mongodb cloud! :)");
  })
  .catch((err) => {
    console.log(err);
  });

// middlewares
app.use(express.urlencoded({ extended: true }));
//app.use(express.static("public"));
app.set("view engine", "ejs");

app.use(express.static(__dirname + '/views'));]

app
  .get("/post/:id", authenticateUser, async (req, res) => {
    const { id } = req.params;
    const getPost = await Post.findOne({ _id: id});
    const warned = await Post.findOne({ warned: String});

    const getusername = await User.findOne({ username: String });

 if(id === null) {
    res.redirect("/home")
  }

   //This is where I try to find the post and all the array's to reference when the post is loaded
   const getCommentsAll = await Post.findOne().toArray() 

  console.log("Displaying all comments for " + `post ${id}\n\n` + getCommentsAll);
 
//Where I reference when the post is loaded
    res.render("particularPost", { warned: warned, comments: getCommentsAll, user: req.session.user, post: getPost, postedBy: getusername });
  
})

发布 Mongoose 架构

const mongoose = require("mongoose");

const PostSchema = new mongoose.Schema({

  title: {
    type: String,
    required: true,
  },
  content: {
    type: String,
    required: true,
  },
  postedAt: {
    type: String,
    default: new Date().toString(),
  },
  postedBy: {
    type: String,
  },
  warned: {
    type: String,
  },
  comment: [Object]
});

module.exports = new mongoose.model("Post", PostSchema);

【问题讨论】:

  • 你没有处理承诺拒绝 1 和 2 findOne 方法不能那样工作

标签: node.js arrays mongodb


【解决方案1】:

这是因为 toArray 对于方法 findOne 不存在,因为 findOne 只返回一个对象。所以正确的实现应该是

await Post.findOne({ ... })


toArray 只能链接在返回多个文档的方法之后,例如 find 方法。

await Post.find({ ... }).toArray()


编辑

我的错。我错过了您使用猫鼬的事实。 .toArray() 只有在使用 MongoDB 原生驱动时才需要。 Mongoose 会为您解决这个问题。你应该可以只写Post.find({ ... }),mongoose 会为你返回一个数组。

https://mongoosejs.com/docs/api.html#model_Model.find

【讨论】:

  • 谢谢,这真的很快,但我仍然收到错误UnhandledPromiseRejectionWarning: TypeError: Post.find(...).toArray is not a function
  • 谢谢它确实有效,但是当用户加载帖子时,我将如何做到这一点,每个数组都单独显示。
  • 每个数组单独显示是什么意思?请详细说明。
  • 我所说的每个数组单独显示的意思是,在第一个数组被投影后,该数组将显示在下一行。
  • 您的意思是要先显示到实际的 Post 文档,然后在单独的 console.logs 中显示 cmets 数组?
猜你喜欢
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 2015-08-14
  • 1970-01-01
  • 2020-11-25
  • 2014-05-09
  • 2013-10-20
相关资源
最近更新 更多