简体   繁体   English

如何使用mongoose从MongoDB中检索单个文档到javascript?

[英]How to retrieve single docs from MongoDB into javascript using mongoose?

I'm trying to get a single document from a mongodb collection and use that document as an object in javascript. 我正在尝试从mongodb集合中获取单个文档,并将该文档用作javascript中的对象。 The problem is that the json that I need to store it as a plain object in javascript only comes when I call it from a response.json(doc) and I can't access that doc outside the function. 问题是我需要将它作为普通对象存储在javascript中的json只有在我从response.json(doc)调用它时才会出现,并且我无法在函数外部访问该doc。 All the info I found is so confusing! 我发现的所有信息都令人困惑!

Is it possible to have something like this: 有可能有这样的事情:

var a = mongoose.model('collectionName').findOne() //etc.

Just get the whole document and transform it into a javascript object accessible in the global scope, so I can get properties from a whenever I please. 刚刚获得整份文件,并将其转化为在全球范围内访问的JavaScript对象,这样我就可以从得到的属性a每当我请。

It sounds like you have a problem with node.js callbacks. 听起来你对node.js回调有问题。 This is not only with mongoose, but any code you write for node.js will look like this: 这不仅适用于mongoose,但您为node.js编写的任何代码都将如下所示:

app.get('/users', function (req, res) {
    Model.find({}, function (err, docs) {
        res.json(docs);
    });
});

So you just nest the callbacks until you have everything you need to send the response. 所以你只需嵌套回调,直到你拥有发送响应所需的一切。

You need to get used to this style of programming. 你需要习惯这种编程风格。 Once you are comfortable with this, you will notice that sometimes the nesting becomes too deep ( callback hell ). 一旦你对此感到满意,你会注意到有时嵌套变得太深( 回调地狱 )。

And there are solutions to that - split your callbacks into individual functions or use async , promises , es6 generators . 并且有解决方案 - 将您的回调拆分为单独的函数或使用asyncpromiseses6生成器

But first, you need to understand the way it is done "naturally". 但首先,你需要理解“自然地”完成它的方式。

A primary concept of NodeJS (and therefore using MongoDB with it) is the async nature of the code you are writing. NodeJS的主要概念(因此使用MongoDB)是您正在编写的代码的异步性质。 Any queries you make to your database will happen asynchronously to the rest of your code's execution. 您对数据库进行的任何查询都将与代码的其余执行异步发生。 For this reason, you will need to pass a callback function with your query so that when the query is completed, your callback function will be executed. 因此,您需要使用查询传递回调函数,以便在查询完成时,将执行回调函数。 Any variables you want to assign to the result of your query should be done in that callback. 您要分配给查询结果的任何变量都应该在该回调中完成。

For example: 例如:

mongoose.model('collectionName').findOne( { ' some query here' }, function(err, doc) {
    // set some variable to the 'doc' result if you want
    // put any logic here to handle the result
});

Any code you put inside the callback method will be executed when the query completed. 您在回调方法中放入的任何代码都将在查询完成时执行。 So you should always check for the existence of an error before doing anything with the resulting document(s). 因此,在对结果文档执行任何操作之前,应始终检查是否存在错误。

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

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