我正在建立一个 node .js应用程序,是一个REST api,在我的mongodb中使用express和mongoose.我现在已经把CRUD端点都设置好了,但我只是想知道两件事.

  1. 我如何扩展这种路由方式,特别是如何在路由之间共享模块.我希望我的每一条路由都放在一个新文件中,但显然只有一个数据库连接,正如你所看到的,我把mongoose 放在了人的顶端.js.

  2. 我必须在我的员工中写下三次模型的模式吗.js?第一个模式定义了模型,然后我在createPerson和updatePerson函数中列出了所有变量.这感觉就像我当年制作php/mysql CRUD时的样子.对于更新函数,我try 编写一个循环,通过"p"来自动检测要更新的字段,但没有效果.任何提示或建议都很好.

此外,我喜欢对整个应用程序发表任何意见,因为对node来说是新手,很难知道你做事情的方式是最有效或"最佳"的做法.谢谢

应用程序.js

// Node Modules
var express     = require('express');
    app         = express();
    app.port    = 3000;



// Routes
var people      = require('./routes/people');

/*
var locations   = require('./routes/locations');
var menus       = require('./routes/menus');
var products    = require('./routes/products');
*/


// Node Configure
app.configure(function(){
  app.use(express.bodyParser());
  app.use(app.router);
});



// Start the server on port 3000
app.listen(app.port);



/*********
ENDPOINTS 
*********/

// People
app.get('/people', people.allPeople); // Return all people
app.post('/people', people.createPerson); // Create A Person
app.get('/people/:id', people.personById); // Return person by id
app.put('/people/:id', people.updatePerson); // Update a person by id
app.delete('/people/:id', people.deletePerson); // Delete a person by id

console.log('Server started on port ' + app.port);

人js

//Database
var mongoose = require("mongoose");
mongoose.connect('mongodb://Shans-MacBook-Pro.local/lantern/');


// Schema
var Schema = mongoose.Schema;  
var Person = new Schema({  
    first_name: String,
    last_name: String,
    address: {
        unit: Number,
        address: String,
        zipcode: String,
        city: String,
        region: String,
        country: String
    },
    image: String, 
    job_title: String,
    created_at: { type: Date, default: Date.now },
    active_until: { type: Date, default: null },
    hourly_wage: Number,
    store_id: Number, // Inheirit store info
    employee_number: Number

});
var PersonModel = mongoose.model('Person', Person);  


// Return all people
exports.allPeople = function(req, res){
    return PersonModel.find(function (err, person) {
      if (!err) {
        return res.send(person);
      } else {
        return res.send(err);
      }
    });
}


// Create A Person
exports.createPerson = function(req, res){
    var person = new PersonModel({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        address: {
            unit: req.body.address.unit,
            address: req.body.address.address,
            zipcode: req.body.address.zipcode,
            city: req.body.address.city,
            region: req.body.address.region,
            country: req.body.address.country
        },
        image: req.body.image,
        job_title: req.body.job_title,
        hourly_wage: req.body.hourly_wage,
        store_id: req.body.location,
        employee_number: req.body.employee_number
    });

    person.save(function (err) {
        if (!err) {
            return res.send(person);
        } else {
            console.log(err);
            return res.send(404, { error: "Person was not created." });
        }
    });

    return res.send(person);
}


// Return person by id
exports.personById = function (req, res){
  return PersonModel.findById(req.params.id, function (err, person) {
    if (!err) {
        return res.send(person);
    } else {
        console.log(err);
        return res.send(404, { error: "That person doesn't exist." });
    }
  });
}


// Delete a person by id
exports.deletePerson = function (req, res){
  return PersonModel.findById(req.params.id, function (err, person) {
    return person.remove(function (err) {
      if (!err) {
          return res.send(person.id + " deleted");
      } else {
          console.log(err);
          return res.send(404, { error: "Person was not deleted." });
      }
    });
  });
}



// Update a person by id
exports.updatePerson = function(req, res){
    return PersonModel.findById(req.params.id, function(err, p){        
        if(!p){
            return res.send(err)
        } else {
            p.first_name = req.body.first_name;
            p.last_name = req.body.last_name;
            p.address.unit = req.body.address.unit;
            p.address.address = req.body.address.address;
            p.address.zipcode = req.body.address.zipcode;
            p.address.city = req.body.address.city;
            p.address.region = req.body.address.region;
            p.address.country = req.body.address.country;
            p.image = req.body.image;
            p.job_title = req.body.job_title;
            p.hourly_wage = req.body.hourly_wage;
            p.store_id = req.body.location;
            p.employee_number = req.body.employee_number;

            p.save(function(err){
                if(!err){
                    return res.send(p);
                } else {
                    console.log(err);
                    return res.send(404, { error: "Person was not updated." });
                }
            });
        }
    });
}

推荐答案

我在这里采取了另一种方法.不是说这是最好的,但让我解释一下.

  1. 每个模式(和模型)都位于自己的文件(模块)中
  2. 特定REST资源的每组路由都位于各自的文件(模块)中
  3. 每个路由模块只需要require个Mongoose模型(仅1个)
  4. 主文件(应用程序入口点)只需将所有路由模块发送require秒即可注册.
  5. Mongo连接位于根文件中,并作为参数传递给任何需要它的地方.

我的应用程序根目录下有两个子文件夹——routesschemas.

这种方法的好处是:

  • 只需编写一次模式.
  • 每个REST资源(CRUD)注册4-5条路由不会污染主应用程序文件
  • 只定义一次DB连接

以下是特定架构文件的外观:

File: /schemas/theaterSchema.js

module.exports = function(db) {
        return db.model('Theater', TheaterSchema());
}

function TheaterSchema () {
        var Schema = require('mongoose').Schema;

        return new Schema({
            title: { type: String, required: true },
            description: { type: String, required: true },
            address: { type: String, required: true },
            latitude: { type: Number, required: false },
            longitude: { type: Number, required: false },
            phone: { type: String, required: false }
    });
}

以下是特定资源的路由集合的外观:

File: /routes/theaters.js

module.exports = function (app, options) {

    var mongoose = options.mongoose;
    var Schema = options.mongoose.Schema;
    var db = options.db;

    var TheaterModel = require('../schemas/theaterSchema')(db);

    app.get('/api/theaters', function (req, res) {
            var qSkip = req.query.skip;
            var qTake = req.query.take;
            var qSort = req.query.sort;
            var qFilter = req.query.filter;
            return TheaterModel.find().sort(qSort).skip(qSkip).limit(qTake)
            .exec(function (err, theaters) {
                    // more code
            });
    });

    app.post('/api/theaters', function (req, res) {
      var theater;

      theater.save(function (err) {
        // more code
      });
      return res.send(theater);
    });

    app.get('/api/theaters/:id', function (req, res) {
      return TheaterModel.findById(req.params.id, function (err, theater) {
        // more code
      });
    });

    app.put('/api/theaters/:id', function (req, res) {
      return TheaterModel.findById(req.params.id, function (err, theater) {
        // more code
      });
    });

    app.delete('/api/theaters/:id', function (req, res) {
      return TheaterModel.findById(req.params.id, function (err, theater) {
        return theater.remove(function (err) {
          // more code
        });
      });
    });
};

下面是根应用程序文件,它初始化了连接并注册了所有路由:

File: app.js

var application_root = __dirname,
        express = require('express'),
        path = require('path'),
        mongoose = require('mongoose'),
        http = require('http');

var app = express();

var dbProduction = mongoose.createConnection('mongodb://here_insert_the_mongo_connection_string');

app.configure(function () {
        app.use(express.bodyParser());
        app.use(express.methodOverride());
        app.use(app.router);
        app.use(express.static(path.join(application_root, "public")));
        app.use('/images/tmb', express.static(path.join(application_root, "images/tmb")));
        app.use('/images/plays', express.static(path.join(application_root, "images/plays")));
        app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.get('/api', function (req, res) {
        res.send('API is running');
});

var theatersApi = require('./routes/theaters')(app, { 'mongoose': mongoose, 'db': dbProduction });
// more code

app.listen(4242);

希望这有帮助.

Mongodb相关问答推荐

MongoDB Aggregate:查找每个月的交叉日期范围的数量

如何在MongoDB中通过限制和跳过查找项进行匹配

使用MongoDB 4将根文档替换为数组

在数组对象 Mongodb 中仅 Select 需要的数组

MongoDB - 将对象转换为数组

pymongo - ifnull 重新调整整个对象而不是特定字段

MongoDB 按 created_at 月聚合

管道聚合mongodb同一$project阶段的计算字段?

通过 docker 运行的 MongoDB 服务器无法互相看到(名称解析中的临时故障)

我怎样才能排序空值在 mongodb 中是最后排序的?

oplog 在独立 mongod 上启用,不适用于副本集

Mongoose 连接认证失败

在 mongodb 中的索引列上查找重复项的快速方法

C# MongoDB 驱动程序 - 如何使用 UpdateDefinitionBuilder?

如何将转储文件夹导入 mongodb 数据库?

从 nodejs 到 mongodb 或 mongoose 的动态数据库连接

将新值推送到 mongodb 内部数组 - mongodb/php

MongoDb 连接被拒绝

是否可以使用聚合框架对 MongoDB 中的 2 个字段求和?

如何从集合中删除除 MongoDB 中的文档之外的所有文档