MongoDB:如何定义模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16998998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB: How to define a schema?
提问by Ayrx
So I have an application that uses MongoDB as a database. The application makes use of a few collections.
所以我有一个使用 MongoDB 作为数据库的应用程序。该应用程序使用了一些集合。
When and how should I go about defining the "schema" of the database which includes setting up all the collections as well as indexes needed?
我应该何时以及如何定义数据库的“架构”,其中包括设置所有集合以及所需的索引?
AFAIK, you are unable to define empty collections in MongoDB (correct me if I am wrong, if I can do this it will basically answer this question). Should I insert a dummy value for each collection and use that to setup all my indexes?
AFAIK,您无法在 MongoDB 中定义空集合(如果我错了,请纠正我,如果我能做到,它基本上会回答这个问题)。我应该为每个集合插入一个虚拟值并使用它来设置我的所有索引吗?
What is the best practice for this?
这方面的最佳做法是什么?
采纳答案by kirelagin
You don't create collections in MongoDB.
You just start using them immediately whether they “exist” or not.
您不在 MongoDB 中创建集合。
无论它们“存在”与否,您都可以立即开始使用它们。
Now to defining the “schema”. As I said, you just start using a collection, so, if you need to ensure an index, just go ahead and do this. No collection creation. Any collection will effectively be created when you first modify it (creating an index counts).
现在来定义“模式”。正如我所说,您只是开始使用集合,因此,如果您需要确保索引,请继续执行此操作。没有集合创建。当您第一次修改它(创建索引计数)时,将有效地创建任何集合。
> db.no_such_collection.getIndices()
[ ]
> db.no_such_collection.ensureIndex({whatever: 1})
> db.no_such_collection.getIndices()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.no_such_collection",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"whatever" : 1
},
"ns" : "test.no_such_collection",
"name" : "whatever_1"
}
]
回答by DevWL
Create empty collection
创建空集合
First of all this is how you can create empty collection in MongoDB using build in interactive terminal, so you can do it,
首先,这是如何使用交互式终端中的构建在 MongoDB 中创建空集合,因此您可以这样做,
db.createCollection('someName'); // create empty collection
just you don't have to because as someone said before they will get created in real time once you start interact with database.
只是您不必这样做,因为正如之前有人所说,一旦您开始与数据库交互,它们就会实时创建。
MongoDB is schema-less end of story but ...
MongoDB 是无模式的故事结局,但是......
You could create your own class that interacts with mongo Database. In that class you could define rules that have to fulfilled before it can insert data to mongo collection other wise throw custom exception.
您可以创建自己的与 mongo 数据库交互的类。在该类中,您可以定义必须满足的规则,然后才能将数据插入到 mongo 集合中,否则抛出自定义异常。
Or if you using node.js server-side you could install mongoosenode package which allows you to interact with database in OOP style (Why bother to reinvent the wheel, right?).
或者,如果您使用 node.js 服务器端,您可以安装mongoose节点包,它允许您以 OOP 风格与数据库交互(为什么要重新发明轮子,对吧?)。
Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
Mongoose 提供了一种直接的、基于模式的解决方案来为您的应用程序数据建模。它包括开箱即用的内置类型转换、验证、查询构建、业务逻辑挂钩等。
docs:mongoose npm installation and basic usage https://www.npmjs.com/package/mongoosemongoose full documentation http://mongoosejs.com
文档:mongoose npm 安装和基本使用 https://www.npmjs.com/package/mongoosemongoose 完整文档http://mongoosejs.com
Mongoose use example (defining schema and inserting data)
Mongoose 使用示例(定义模式和插入数据)
var personSchema = new Schema({
name: { type: String, default: 'anonymous' },
age: { type: Number, min: 18, index: true },
bio: { type: String, match: /[a-zA-Z ]/ },
date: { type: Date, default: Date.now },
});
var personModel = mongoose.model('Person', personSchema);
var comment1 = new personModel({
name: 'Witkor',
age: '29',
bio: 'Description',
});
comment1.save(function (err, comment) {
if (err) console.log(err);
else console.log('fallowing comment was saved:', comment);
});
Bla bla bla...
啦啦啦啦啦...
Being able to set schema along with restriction in our code desn't change the fact that MongoDB itself is schema-less which in some scenarios is actuality an advantage. This way if you ever decide to make changes to schema but you don't bother about backward compatibility just edit schema in your script and you are done. This is the basic idea behind the mongodb to be able to store different sets of data in each document with in same collection. However some restriction in code base logic are always desirable.
能够在我们的代码中设置模式和限制并不会改变 MongoDB 本身是无模式的事实,这在某些情况下实际上是一个优势。这样,如果您决定对架构进行更改,但又不担心向后兼容性,只需在脚本中编辑架构即可。这是 mongodb 背后的基本思想,即能够在同一集合中的每个文档中存储不同的数据集。然而,代码库逻辑中的一些限制总是可取的。
回答by Jonno_FTW
As of version 3.2, mongodb now provides schema validation at the collection level:
从 version 3.2 开始,mongodb 现在在集合级别提供模式验证:
回答by Boris Stitnicky
You have already been taught that MongoDB is schemaless. However, in practice, we have a kind of "schema", and that is the object space of the object, whose relations a MongoDB database represents. With the ceveat that Ruby is my go-to language, and that I make no claims about exhaustiveness of this answer, I recommend to try two pieces of software:
您已经被告知 MongoDB 是无模式的。但是,在实践中,我们有一种“模式”,那就是对象的对象空间,MongoDB 数据库表示其关系。考虑到 Ruby 是我的首选语言,并且我不声称此答案的详尽性,我建议尝试两个软件:
1. ActiveRecord (part of Rails)
2. Mongoid (standalone MongoDB "schema", or rather, object persistence system in Ruby)
Expect a learning curve, though. I hope that others will point you to solutions in other great languages outside my expertise, such as Python.
不过,预计会有一个学习曲线。我希望其他人会向您指出我的专业知识之外的其他优秀语言的解决方案,例如 Python。
回答by Ashwath Halemane
1.Install mongoose:
npm install mongoose
2. Set-up connection string and call-backs
// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
//call-backs
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
3. Write your schema
var kittySchema = new mongoose.Schema({
name: String
});
4. Model the schema
var Kitten = mongoose.model('Kitten', kittySchema);
5. Create a document
var silence = new Kitten({ name: 'Tom' });
console.log(silence.name); // Prints 'Tom' to console
// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
enter code here
var Kitten = mongoose.model('Kitten', kittySchema);
Functions added to the methods property of a schema get compiled into the Model prototype and exposed on each document instance:
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"