node.js 将查找查询中的结果猫鼬返回到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24035872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return results mongoose in find query to a variable
提问by Xanarus
I need to return the results of a query with mongoose in node.js.
我需要在 node.js 中使用 mongoose 返回查询结果。
How do you return the value to set the value to a variable?
如何返回值以将值设置为变量?
What I need to do is:
我需要做的是:
var results = users.findOne({_id : users_list[i]['user_id']},{email : 1, credits : 1},{}, function(err, docs) {
if( err || !docs) {
console.log("No user found");
} else {
return docs;
};
});
In order to have:
为了有:
results = docs
Thanks a lot for your reply .
非常感谢您的回复 。
I also have another problem.
我还有另一个问题。
How to pass variable in a query operator with find or findOne? Like :
如何使用 find 或 findOne 在查询运算符中传递变量?喜欢 :
var foo = "Blaa";
users.findOne({_id : users_list[i]['user_id']},{email : 1, credits : 1},{}, function(err, docs) {
if( err || !docs) {
console.log("No user found");
} else {
// I want to use the foo variable here
console.log(foo);
};
});
回答by Edwin Dalorzo
There are several ways to achieve what you want.
有几种方法可以实现您想要的。
1. Using Mongoose Queries
1. 使用猫鼬查询
In this strategy, your function returns a Mongoose query which you can later use to invoke the method execand use it to get the results.
在此策略中,您的函数返回一个 Mongoose 查询,您可以稍后使用它来调用该方法exec并使用它来获取结果。
function getJedisQuery(name){
var query = Jedi.find({name:name});
return query;
}
Then you can use it simply doing:
然后你可以简单地使用它:
var query = getJedisQuery('Obi-wan');
query.exec(function(err,jedis){
if(err)
return console.log(err);
jedis.forEach(function(jedi){
console.log(jedi.name);
});
});
2. Using Mongoose Promise-like Objects
2. 使用 Mongoose Promise-like 对象
Moogose provides support for promise-like objects. All you have to do is something somewhat similar to what I did above, but this time, you invoke the execmethod without a callback.
Moogose 为类似 Promise 的对象提供支持。您所要做的就是与我上面所做的有些相似,但是这一次,您exec无需回调即可调用该方法。
function getJedisPromise(name){
var promise = Jedi.find({name:name}).exec();
return promise;
}
Then you can use it by simply doing:
然后你可以通过简单地使用它:
var promise = getJedisPromise('Luke');
promise.then(function(jedis){
jedis.forEach(function(jedi){
console.log(jedi.name);
});
})
As highlighted in the comment section of this answer, these objects are not in fact promises and that needs to be taken into account (see Queries are not promises).
正如本答案的评论部分所强调的那样,这些对象实际上并不是承诺,需要考虑到这一点(请参阅查询不是承诺)。
3. Using Mongoose Streams
3. 使用猫鼬流
Finally, Mongoose has also support for streams and streams are event emitters. So, you could get a stream and then subscribe for 'data' and 'error' events. Like this:
最后,Mongoose 还支持流,并且流是事件发射器。因此,您可以获得一个流,然后订阅“数据”和“错误”事件。像这样:
function getjedisStream(name){
var stream = Jedi.find({name:name}).stream();
return stream;
}
Then you can simply do:
然后你可以简单地做:
var stream = getJedisStream('Anakin');
stream.on('data', function(jedis){
jedis.forEach(function(jedi){
console.log(jedi.name);
});
});
stream.on('error', function(error){
console.log(error);
});
Source, for future reference.
来源,供以后参考。
回答by Javad.mrz
It is being executed before the assignment.
它正在分配之前执行。
async function(req, res) {
var user;
await users.findOne({}, function(err,pro){
user=pro;
});
console.log(user); \ it's define
};
回答by Kavale arun
You can easily achieve this.
您可以轻松实现这一目标。
const getUser = async ( req, res ) => {
let users = () => ( User.find({_id : users_list[i]['user_id']},{email : 1, credits : 1}).exec() );
try { res.send({"user":await users() });}
catch(e) { console.log(e) }
}
app.get('/user' , getUser);
回答by Surender Singh
You achieve the desired result by the following code. Hope this will helps you a lot..
您可以通过以下代码获得所需的结果。希望这会帮助你很多..
var async = require('async');
// custom imports
var User = require('../models/user');
var Article = require('../models/article');
var List1Objects = User.find({});
var List2Objects = Article.find({});
var resourcesStack = {
usersList: List1Objects.exec.bind(List1Objects),
articlesList: List2Objects.exec.bind(List2Objects),
};
async.parallel(resourcesStack, function (error, resultSet){
if (error) {
res.status(500).send(error);
return;
}
res.render('home', resultSet);
});

