带Mongodb的javascript我需要从Mongodb中的db获取一些信息

带Mongodb的javascript我需要从Mongodb中的db获取一些信息,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我写这篇文章是因为我正在用Javascript编写一个程序,需要连接到MongoDB,我获得了一个教程,可以连接到数据库并插入元素,如: var insertDocuments = function(db, callback) { // Get the documents collection var collection = db.collection('documents'); // Insert some documents collection.insertMany([ {name

我写这篇文章是因为我正在用Javascript编写一个程序,需要连接到MongoDB,我获得了一个教程,可以连接到数据库并插入元素,如:

var insertDocuments = function(db, callback) {
  // Get the documents collection
var collection = db.collection('documents');
 // Insert some documents
collection.insertMany([
{name: "Guns N' Roses", members: ['Axl Rose', 'Slash', 'Izzy Stradlin','Matt Sorum', 'Duff McKagan'], year: 1986}], function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
assert.equal(1, result.ops.length);
console.log("Inserted 3 documents into the document collection");
callback(result);
});
}

var findDocuments = function(db, callback) {
 // Get the documents collection
var collection = db.collection('documents');
 // Insert some documents
collection.find([], function(err, result) {
assert.equal(err, null);
console.log(result);
callback(result);
 });
}

有了它,我成功地在数据库中插入了代码,但现在我需要从数据库中提取信息,并将其分配给一个变量,以便在其余的Javascript代码中使用,我不知道如何进行。你们能帮我一下吗?

我不知道你们在node js中使用的是哪个库,我通常使用mongoose,使用起来非常直观

这里有一个链接,指向您可以阅读的文档

对于mongo的数据,你必须这样做

collection.find(function (err, collection) {
  if (err) return console.error(err);
    within the function you can do the searches you want,
    save them in variables and use then outside this function 
 console.log(collection);
})
如果你意识到这与我们在你的例子中已经得到的非常相似