问题描述
我需要在node.js中用猫鼬返回查询结果.
I need to return the results of a query with mongoose in node.js.
如何返回值以将值设置为变量?
How do you return the value to set the value to a variable?
我需要做的是:
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;
};
});
要拥有:
results = docs
非常感谢您的答复.
我还有另一个问题.
如何使用find或findOne在查询运算符中传递变量?像:
How to pass variable in a query operator with find or findOne? Like :
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);
};
});
推荐答案
有几种方法可以实现所需的目标.
There are several ways to achieve what you want.
1.使用猫鼬查询
在这种策略中,您的函数返回一个Mongoose查询,您以后可以使用该查询来调用方法exec
并使用它来获取结果.
In this strategy, your function returns a Mongoose query which you can later use to invoke the method exec
and use it to get the results.
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.使用类似猫鼬的诺言对象
Moogose为类似诺言的对象提供支持.您所要做的只是与我上面所做的类似,但是这次,您调用了exec
方法而没有回调.
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 exec
method without a callback.
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.使用猫鼬流
最后,猫鼬还支持流,并且流是事件发射器.因此,您可以获取流,然后订阅数据"和错误"事件.像这样:
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:
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);
});
来源,以供将来参考.
这篇关于将查找查询中的结果猫鼬返回给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!