简体   繁体   English

用于模式定义的猫鼬或 MongoDB?

[英]Mongoose or MongoDB for Schema definition?

Mongoose is used to define a schema. Mongoose 用于定义模式。 right?对? Is it is possible to create a schema with mongoDB through mongo Shell ?是否可以通过 mongo Shell 使用 mongoDB 创建模式? like喜欢

eg: name:String例如:名称:字符串

MongoDB doesn't support schema. MongoDB 不支持架构。 It's a schemaless document based DB.它是一个基于无模式文档的数据库。

Mongoose is an ODM(Object Document Mapper) that helps to interact with MongoDB via schema, plus it also support validations & hooks. Mongoose 是一个 ODM(对象文档映射器),它有助于通过模式与 MongoDB 交互,此外它还支持验证和钩子。

Basically mongodb is schema less database we cant able to create schema directly in mongodb.基本上 mongodb 是无模式的数据库,我们无法直接在 mongodb 中创建模式。 Using mongoose we can able to create a schema.使用 mongoose 我们可以创建一个模式。 Simple CRUD operation using mongoose, for more info ref this link使用猫鼬的简单 CRUD 操作,有关更多信息,请参阅此链接

package.json包.json

{
    "name": "product-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "body-parser": "~1.0.1",
        "cors": "2.8.1",
        "mongoose": "~3.6.13"
    }
}

product.js产品.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var ProductSchema   = new Schema({
    title: String,
    price: Number,
    instock : Boolean,
    photo : String ,
});
module.exports = mongoose.model('Product', ProductSchema);
// module.exports = mongoose.model('Product', ProductSchema,'optiponally pass schema name ');

server.js服务器.js

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();

mongoose.connect('mongodb://localhost:27017/products');

// Middle Route 

router.use(function (req, res, next) {
    // do logging 
    // do authentication 
    console.log('Logging of request will be done here');
    next(); // make sure we go to the next routes and don't stop here
});


router.route('/products').post(function (req, res) {
    console.log("in add");
    var p = new product();
    p.title = req.body.title;
    p.price = req.body.price;
    p.instock = req.body.instock;
    p.photo = req.body.photo;
    p.save(function (err) {
        if (err) {
            res.send(err);
        }
        console.log("added");
        res.send({ message: 'Product Created !' })
    })
});

router.route('/products').get(function (req, res) {
    product.find(function (err, products) {
        if (err) {
            res.send(err);
        }
        res.send(products);
    });
});

router.route('/products/:product_id').get(function (req, res) {


    product.findById(req.params.product_id, function (err, prod) {
        if (err)
            res.send(err);
        res.json(prod);
    });
});

router.route('/products/:product_id').put(function (req, res) {

    product.findById(req.params.product_id, function (err, prod) {
        if (err) {
            res.send(err);
        }
        prod.title = req.body.title;
        prod.price = req.body.price;
        prod.instock = req.body.instock;
        prod.photo = req.body.photo;
        prod.save(function (err) {
            if (err)
                res.send(err);

            res.json({ message: 'Product updated!' });
        });

    });
});

router.route('/products/:product_id').delete(function (req, res) {

    product.remove({ _id: req.param.product_id }, function (err, prod) {
        if (err) {
            res.send(err);
        }
        res.json({ message: 'Successfully deleted' });
    })

});


app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);

Mongoose helps to interact with MongoDB in terms of Object/Model so that programmer doesn't need to understand the remember the statements of MongoDB. Mongoose 帮助在 Object/Model 方面与 MongoDB 进行交互,这样程序员不需要理解记住 MongoDB 的语句。

Also, Mongoose provides lot of methods of CRUD Operations to better understanding of DB Operations.此外,Mongoose 提供了很多 CRUD 操作的方法来更好地理解 DB 操作。

You can check examples here您可以在此处查看示例

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose http://mongoosejs.com/docs/ https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose http://mongoosejs.com/docs/

Mongoose has its benefits of validation and schema configurations but it has its cons of latency and some problems with high/mid scale applications. Mongoose 有其验证和模式配置的优点,但也有延迟和一些高/中规模应用程序的问题。

it's always the best thing IMHO, to use the native mongodb package.恕我直言,使用本机 mongodb 包总是最好的。

regarding schema, you can create your own "schema" as a json file and write ur own validations for mandatory or valid attributes.关于架构,您可以创建自己的“架构”作为 json 文件,并为强制性或有效属性编写自己的验证。

it's faster, with no third party packages and more reliable.它更快,没有第三方软件包,更可靠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM