如何解决如何在node.js上使用mongoose从mongodb基础检索文档?
我试图找到有关从mongodb检索数据的任何信息,但是每个人都展示了如何使用新模型而不是已经创建的模型来做到这一点。我该怎么办?
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/acme",{
useNewUrlParser: true,useUnifiedTopology: true,});
const db = mongoose.connection;
db.on("error",console.error.bind(console,"connection error:"));
db.once("open",function () {
console.log("WERE CONNECTED");
});
mongoose.model("posts",{ title: String });
const post = mongoose.model("posts").find({ title: "Post One" });
console.log("post",post);
解决方法
您需要致电.find
作为建模承诺,
const post = mongoose.model("posts",{ title: String });
async function findMethod(){
console.log("post",await post.find({ title: "Post One" }))
}
findMethod();
,
find
方法返回promise
并接受callback
两种检索documents
使用callback
const Post = mongoose.model("posts",{ title: String });
Post.find({ title: "Post One" },(err,result) => {
// ...your result
})
使用async
await
const Post = mongoose.model("posts",{ title: String });
const find = async() => {
const post = await Post.find({ title: "Post One" })
console.log("post:",post)
}
find();
如果只需要第一个文档,则可以使用findOne()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。