构造文档产生半空结果

时间:2014-10-31 14:50:55

标签: express mongoose

执行Customer.create({customerName:'John'})后,创建以下文档时没有错误且没有'customerName'节点。

有谁能告诉我为什么这个看似简单的文档创建调用会产生一个半空白的文档?来自Mongoose的响应中的文档与数据库本身中的文档相同。

我无法判断我是否错误地使用了Mongoose或Express。在此先感谢您的帮助。

{ __v: 0, _id: 5452dc48d687bad849d70816 }

路由/ customer.js

var mongoose = require( 'mongoose' );
var Customer = mongoose.model( 'Customer');

exports.create = function(req, res) {
    Customer.create({
        customerName: 'John'
    }, function(err, customer) {
        if (err) return err;
        console.log('Customer created', customer);
        res.send(customer);
    });
}

架构/ customer.js

var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
    customerName: {
        type: String,
        required: false
    }
});

db.js

var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/CustomerDatabase';
mongoose.connect(dbURI);

var customerSchema = require( '../schema/customer.js' );
var Customer = mongoose.model( 'Customer', customerSchema);

routes.js

function SetupRoutes(app, PATH) {
    var db = require('../model/db.js')
    var customer = require( '../routes/customer.js' );
    app.post('/Customer', customer.create);
}

module.exports.SetupRoutes = SetupRoutes;

1 个答案:

答案 0 :(得分:1)

您需要从customer.js导出customerSchema,以便在db.js需要该文件时,其值为导出的模式:

var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
    customerName: {
        type: String,
        required: false
    }
});
module.exports = customerSchema;

但是,更典型的模式是在customer.js中创建模型,然后导出:

var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
    customerName: {
        type: String,
        required: false
    }
});
module.exports = mongoose.model('Customer', customerSchema);