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

时间:2015-10-07 19:13:05

标签: 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: "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代码,我不知道如何。你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

我不知道你在节点js中使用哪个库,我通常使用非常直观的mongoose。

以下是您可以阅读的文档的链接

http://mongoosejs.com/

对于关于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);
})

如果您发现它与我们在您的示例中已有的非常相似