Luis Rabock
Luis Rabock

Reputation: 1

Mongoose/mongo store findOne into variable

I need do findOne and take the result to a variable to insert in another collection. The problem are inside function i have results, and outsid just empty.

var rest = [];

function queryCollection(collection, callback, city){
    collection.findOne({cidade: city},function(err, result) {
        k = 1
        if (err) {
            console.log(err);
        } else if (k > 0) {
            console.log(result)//here have result
            rest.push(result);
            callback();
            console.log(rest)//here have result
            k - 1;
        }
    });
}

queryCollection(Location, function(){
    console.log(rest);
}, 'FATIMA');
console.log('out', rest)//HERE IS EMPTY, HOW CAN I USE REST VALUE?

Upvotes: 0

Views: 619

Answers (1)

user9111756
user9111756

Reputation:

Here are a couple things to note about javascript and some examples of using mongoose. I hope it helps!

  1. Javascript is not necessarily going to run your code in the order that your statements appear in the source code.
  2. Any operation that you perform in mongoose that connects to the database is going to be asynchronous.

consider this contrived example loosely based on your question:

'use strict';

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;

const testSchema = new Schema({
  city: String
});

const Test = mongoose.model('test', testSchema);

const test = new Test({
  city: 'Tucson'
});

function queryCollection() {
  console.log('queryCollection');
  Test.findOne({ city: test.city }, function (err, result) {
    console.log('findOne callback');
    if (err) {
      return console.error(err);
    } else {
      console.log(`result: ${result}`);
    }
  });
}

test.save(function (err, doc) {
  console.log('save callback');
  if (err) { return console.error(err); }
  queryCollection();
});

console.log('console.log');

shell output

stack: node ./49738064.js
console.log
save callback
queryCollection
findOne callback
result: { _id: 5acbd819e89388d34ea8d6a1, city: 'Tucson', __v: 0 }
^C
stack:

Notice that the very first output from the script is 'console.log' This is due to the fact that test.save() and Test.findOne() are asynchronous operations, meaning that they take time to complete that javascript isn't going to wait around for.

Functions that read from or write to the network, disk, or database are frequently referred to as 'async' unless they are documented/named otherwise. You need to account for this mixture of sync and async operations in your code.

Historically, this was accomplished with callbacks. If there was some operation that was async, a callback was passed into that operation that would handle the results from the async call.

returning to our contrived example from above:

'use strict';

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;

const testSchema = new Schema({
  city: String
});

const Test = mongoose.model('test', testSchema);

const test = new Test({
  city: 'Tucson'
});

function queryCollection(done) {
  Test.findOne({ city: test.city }, function (err, result) {
    if (err) {
      return console.error(err);
    } else {
      done(result);
    }
  });
}

test.save(function (err, doc) {
  if (err) { return console.error(err); }
  queryCollection(console.log);
});

As you can see I passed in the console.log function as the callback to the async query operation. You can write your own functions and pass them in as well.

shell output

stack: node ./49738064.js
{ _id: 5acbd819e89388d34ea8d6a1, city: 'Tucson', __v: 0 }
^C
stack:

A more modern way of dealing with async operations is to use promises. A Promise is an object that represents the future outcome of the operation you are performing.

All of the mongoose async operations return a promise ( or a promise-like object ) by default if you don't pass in a callback. Because of this, they can be used very effectively with async/await.

here is an example of using async await with mongoose:

'use strict';

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;

const testSchema = new Schema({
  city: String
});

const Test = mongoose.model('test', testSchema);

const test = new Test({
  city: 'Tucson'
});

function queryCollection() {
  return Test.findOne({ city: test.city });
}

async function run () {
  await Test.remove({}); // remove all existing documents
  await test.save(); // save the new document
  let found = await queryCollection();
  console.log(found);
}

run();

shell output

stack: node ./49738064.js
{ _id: 5acbdf5dd8dc39d6065c820c, city: 'Tucson', __v: 0 }
^C
stack:

Upvotes: 4

Related Questions