如何将mongodb查询结果分配给变量?

时间:2021-12-03 15:43:05

Now I connect Node.js with mongodb and query databse using express. Say there is schema called Animal, which has an array field called traits. When I query:

现在我使用express连接Node.js和mongodb以及查询数据库。假设有一个名为Animal的模式,它有一个名为traits的数组字段。当我查询时:

db.animals.distinct("traits")

I got the result as:

我的结果如下:

['playful', 'funny', 'lazy', 'loyal']

Is it possible that I pass this result to a variable for later use? Thanks a lot.

是否有可能将此结果传递给变量以供以后使用?非常感谢。

2 个解决方案

#1


0  

first install this library by npm install client-sessions

首先通过npm install client-sessions安装此库

call this in your main js page

在主js页面中调用它

  var session = require('client-sessions');

give definition

给出定义

app.use(session({
  cookieName: 'session',
  secret: 'random_string_goes_here',
  duration: 30 * 60 * 1000,
  activeDuration: 5 * 60 * 1000,
})); 

Store the results in session called animals

将结果存储在名为animals的会话中

    app.post('/getAnimals', function(req, res) {    
     // inside your DB query callback{}
       req.session.animals=  db.animals.distinct("traits")                       
   })

Retrieving data from session when required

在需要时从会话中检索数据

console.log(req.session.animals);   //will give
['playful', 'funny', 'lazy', 'loyal']

console.log(req.session.animals[0]);  // will give first element
playful

Let me know if this solution solved your issue :) ?

如果此解决方案解决了您的问题,请告诉我:)?

#2


0  

Yes. you can assign query result to variable. like this:

是。您可以将查询结果分配给变量。喜欢这个:

var a;
db.collection('animals', function(err, collection) {
    collection.distinct("traits", function(err, results) {
        a = results;
        console.log(results);
    });
});

#1


0  

first install this library by npm install client-sessions

首先通过npm install client-sessions安装此库

call this in your main js page

在主js页面中调用它

  var session = require('client-sessions');

give definition

给出定义

app.use(session({
  cookieName: 'session',
  secret: 'random_string_goes_here',
  duration: 30 * 60 * 1000,
  activeDuration: 5 * 60 * 1000,
})); 

Store the results in session called animals

将结果存储在名为animals的会话中

    app.post('/getAnimals', function(req, res) {    
     // inside your DB query callback{}
       req.session.animals=  db.animals.distinct("traits")                       
   })

Retrieving data from session when required

在需要时从会话中检索数据

console.log(req.session.animals);   //will give
['playful', 'funny', 'lazy', 'loyal']

console.log(req.session.animals[0]);  // will give first element
playful

Let me know if this solution solved your issue :) ?

如果此解决方案解决了您的问题,请告诉我:)?

#2


0  

Yes. you can assign query result to variable. like this:

是。您可以将查询结果分配给变量。喜欢这个:

var a;
db.collection('animals', function(err, collection) {
    collection.distinct("traits", function(err, results) {
        a = results;
        console.log(results);
    });
});