猫鼬:模式与模型? [英] Mongoose: Schema vs Model?

查看:37
本文介绍了猫鼬:模式与模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看教程时,通常会区分模式和模型,尤其是在处理 mongoose/mongodb 时.这使得移植到 postgresql 有点令人困惑,因为在该系统下似乎不存在模型".这两种方法有什么区别?

When looking at tutorials there is often a delineation between a schema and a model, particularly when dealing with mongoose/mongodb. This makes porting over to postgresql somewhat confusing, as 'models' don't seem to exist under that system. What is the difference the two approaches?

例如,这行的 postgres/sql ORM 等价物是什么?

For example, what would be a postgres/sql ORM equivalent of this line?

(猫鼬和 express.js):

(mongoose and express.js):

var userSchema = schema.define('local', {
    username:       String,
    password:       String,
});

module.exports = mongoose.model('User', userSchema);

推荐答案

在 mongoose 中,模式表示特定文档的结构,可以是完整的,也可以只是文档的一部分.这是一种表达预期属性和值以及约束和索引的方式.模型定义了用于与数据库交互(读取、插入、更新等)的编程接口.所以模式会回答这个集合中的数据是什么样的?"并且模型提供诸如是否有任何记录匹配此查询?"之类的功能.或将新文档添加到集合中".

In mongoose, a schema represents the structure of a particular document, either completely or just a portion of the document. It's a way to express expected properties and values as well as constraints and indexes. A model defines a programming interface for interacting with the database (read, insert, update, etc). So a schema answers "what will the data in this collection look like?" and a model provides functionality like "Are there any records matching this query?" or "Add a new document to the collection".

在直接 RDBMS 中,模式由 DDL 语句(创建表、更改表等)实现,而没有模型的直接概念,只有可以执行高度灵活查询(选择语句)以及基本查询的 SQL 语句插入、更新、删除操作.

In straight RDBMS, the schema is implemented by DDL statements (create table, alter table, etc), whereas there's no direct concept of a model, just SQL statements that can do highly flexible queries (select statements) as well as basic insert, update, delete operations.

另一种思考方式是 SQL 的性质允许您通过仅选择特定字段以及将相关表中的记录连接在一起来为每个查询定义模型".

Another way to think of it is the nature of SQL allows you to define a "model" for each query by selecting only particular fields as well as joining records from related tables together.

在 Ruby on Rails 等其他 ORM 系统中,模式是通过 ActiveRecord 机制定义的,模型是您的 Model 子类添加的额外方法,用于定义额外的业务逻辑.

In other ORM systems like Ruby on Rails, the schema is defined via ActiveRecord mechanisms and the model is the extra methods your Model subclass adds that define additional business logic.

这篇关于猫鼬:模式与模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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