繁体   English   中英

如何在 node.js 上使用 mongoose 从 mongodb 库检索文档?

[英]How can I retrieve document from mongodb base using mongoose on node.js?

我试图找到有关从 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调用为 promise 至 model,

const post = mongoose.model("posts", { title: String });
async function findMethod(){
    console.log("post", await post.find({ title: "Post One" }))
}
findMethod();

find方法返回promise并接受callback

2 检索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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM