尽管模式“需要",猫鼬仍保存空记录 [英] Mongoose saving empty record despite schema "require"

查看:54
本文介绍了尽管模式“需要",猫鼬仍保存空记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 Node.js 应用程序,它使用 Mongoose 和 Express 创建一个 RESTful API.Mongoose 模式定义了必填字段;但是,当我通过 Postman 提交空 POST 时,API 会创建空记录.为什么 Mongoose/MongoDB 不会阻止基于我的架构的保存?

I'm creating a Node.js app that uses Mongoose and Express to create a RESTful API. The Mongoose schema defines required fields; however, when I submit an empty POST via Postman, the API creates empty records. Why isn't Mongoose / MongoDB preventing a save based on my schema?

我只是在学习 node.js/express/mongoose/mongodb 并且来自 mySQL/MSSQL 世界,所以我可能会以错误的方式考虑模式所需的字段(即像数据库约束一样)

I'm just learning node.js / express / mongoose / mongodb and coming from a mySQL/MSSQL world so I may be thinking about schema required fields the wrong way (i.e. like a database constraint)

这是我的路由器:

// Initialize controller(s) for CRUD
var customer = require('../controllers/customercontroller');

// Initialize Router
var express = require('express');
var router = express.Router();

router.get('/:id', function (req, res) {
    console.log("Customer Requested");

    customer.read(req, res);
});

router.get('/', function (req, res) {
    console.log("Customer List Requested");
    customer.getList(req, res);
});

router.put("/:id", function (req, res) {
    console.log("Updating Customer");
    customer.update(req, res);

});

router.post("/", function (req, res) {
    console.log("Creating Customer");
    customer.create(req, res);

});

router.delete("/:id", function (req, res) {
    console.log("Delete Customer");
    customer.delete(req, res);
});

module.exports = router;

这是我的控制器:

var Customer = require('../models/customermodel');

exports.getList = function (req, res) {
    Customer.find({}, function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.create = function (req, res) {
    var customer = new Customer(req.body);
    customer.save(function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.read = function (req, res) {
    Customer.find(req.params.id, function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.update = function (req, res) {
    Customer.findOneAndUpdate(req.params.id, function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.delete = function (req, res) {
    Customer.remove({_id: req.params.id}, function (err, customer) {
        if (err)
            res.send(err);
        res.json({ message: 'Customer deleted'});
    });
};

这是我的模型:

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

var Schema = mongoose.Schema;

var CustomerSchema = new Schema({
    "name": { type: String, Required: 'Required: name' },
    "alias": { type: String, Required: 'Required: alias' },
    "email": { type: String, Required: 'Required: email' },
    "address1": { type: String, Required: 'Required: address1' },
    "address2": { type: String, Required: 'Required: address2' },
    "address3": { type: String, Required: 'Required: address3' },
    "city": { type: String, Required: 'Required: city' },
    "state": { type: String, Required: 'Required: state' },
    "postcode": { type: String, Required: 'Required: postcode' },
    "country": { type: String, Required: 'Required: country' },
    "created": { type: Date, Required: 'Required: date' },
});

module.exports = mongoose.model('customer', CustomerSchema);

当我使用 Postman 发布一个空正文并使用 mongo 控制台查询结果时:

When I post an empty body with Postman and query the result with the mongo console:

> db.customers.find()
{ "_id" : ObjectId("591f25ae0cca8f5148cce551"), "__v" : 0 }
{ "_id" : ObjectId("591f25d40cca8f5148cce552"), "__v" : 0 }
{ "_id" : ObjectId("591f25f00cca8f5148cce553"), "__v" : 0 }
{ "_id" : ObjectId("591f2764dc5a191fe8730ccd"), "__v" : 0 }
>

所以,我的问题:

模式不是应该验证数据并阻止类似于 mySQL 或 MSSQL 中的数据库约束的保存吗?还是模式只是为 node.js 控制器提供数据以供参考,需要我创建业务逻辑来强制执行约束?

Isn't the schema supposed to validate the data and prevent the save similar to a database constraint in mySQL or MSSQL? Or does the schema just give data for a node.js controller to reference, requiring me to create business logic to enforce the constraint?

推荐答案

架构属性名称区分大小写,因此将您的 Required 字段更改为 required:

The schema property names are case sensitive, so change your Required fields to required:

var CustomerSchema = new Schema({
    "name": { type: String, required: 'Required: name' },
    "alias": { type: String, required: 'Required: alias' },
    ...

这篇关于尽管模式“需要",猫鼬仍保存空记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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