[MEAN Stack] First API -- 1. with Node.js, Express and MongoDB

Learn how to import data into your MongoDB and then use Express to serve a simple Node.js API.

 

Import data into MongoDB:

For exmaple, you have an data.json file and contains some data. 

1. Start Mongod service:

//in the cmd
$ mongod

2. Open a new Tab, import the data:

mongoimport --db simple --collection people --jsonArray data.json

Import data.json file (a json array file), set database as simple, name it as people collection.

Read More: http://docs.mongodb.org/manual/reference/program/mongoimport/

 

You can play around with those data:

// in cmd

$ mongo

Enter the mongodb cmd-clinet.

 

Find the data:

db.simple.find();
db.simple.findOne();

Remove data:

db.simple.remove()

 

Set up Server:

npm install -S express  mongoose cors 

Server.js:

复制代码
/**
 * Created by Answer1215 on 12/9/2014.
 */
'use strict';

var expres = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/simple');
var cors = require("cors");

var personSchema = {
    firstName:String,
    lastName:String,
    email:String
};

//create a person model, and rename db as people
var Person = mongoose.model('Person', personSchema, 'people');
var app = expres();
app.use(cors());

app.get('/people', function(request, response){
    Person.find(function(err, data) {
        response.json(200, data);
    })
});

app.listen(3000);
复制代码

 

app.js:

复制代码
/**
 * Created by Answer1215 on 12/9/2014.
 */
'use strict';

function MainCtrl(PeopleService) {
    var vm = this;
    vm.people = [];
    
    vm.getPeople = PeopleService.getPeople().then(function(response) {
        vm.people = response.data;
    });
}

function PeopleService($http) {

    var PeopleService = {};
    PeopleService.getPeople = function() {
         return $http.get('http://localhost:3000/people');
    }

    return PeopleService;
}

angular.module('app',[])
    .controller('MainCtrl', MainCtrl)
    .service('PeopleService', PeopleService);
复制代码

 

index.html:

复制代码
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body ng-app="app">

    <div ng-controller="MainCtrl as vm">
        <ul>
            <li ng-repeat="person in vm.people">{{person.firstName}}</li>
        </ul>
    </div>

    <script src="bower_components/angular/angular.min.js"></script>
    <script src="app.js"></script>
</body>
</html>
复制代码

 

posted @   Zhentiw  阅读(339)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示