从MongoDB + Node.js到客户端JavaScript的数据获取 [英] Getting data from MongoDB+Node.js to a client side JavaScript

查看:53
本文介绍了从MongoDB + Node.js到客户端JavaScript的数据获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Node.js连接到MongoDB?然后将结果传递到客户端JavaScript并以HTML显示.

How to connect to MongoDB with Node.js? And then pass the result to a client side JavaScript and display in HTML.

var http = require('http');
var URL = require('url');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('people', new Server("127.0.0.1", 27017, {}), { safe: false });

client.open(function (err, client) {
  client.collection('people', listAllData);
});

var listAllData = function (err, collection) {
  collection.find().toArray(function (err, results) {
    console.log(results);
  });
}

推荐答案

您应该使用Mongoose-用于node.js的优雅mongodb对象建模. http://mongoosejs.com

You should use Mongoose - elegant mongodb object modeling for node.js. http://mongoosejs.com

快速入门指南真的很棒,您应该阅读它.

The quickstart guide is really cool, you should read it.

根据文档,这是一个如何使用猫鼬的小例子:

According to the documentation, here is a small example of how to use Mongoose:

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'test');

var schema = mongoose.Schema({ name: 'string' });
var Cat = db.model('Cat', schema);

var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
  if (err) // ...
  console.log('meow');
});

这篇关于从MongoDB + Node.js到客户端JavaScript的数据获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆