为什么MongoDB需要`unique:true`来创建一个集合? [英] Why does MongoDB require `unique:true` to create a collection?

查看:247
本文介绍了为什么MongoDB需要`unique:true`来创建一个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express和MongoDB开发NodeJS应用程序.我的对象没有保存到数据库中,因此我进行了更深入的挖掘,发现如果使用以下对象,则不会创建目标集合:

I am developing a NodeJS application with Express and MongoDB. My objects were not getting saved to the database, so I dug deeper and I found that the target collection was not created if I used:

const PersonSchema = new Schema({
  firstName: String,
});

如果我使用过,就会创建收藏集

and the collection was created if I used

const PersonSchema = new Schema({
  firstName: { type: String, unique: true},
});

无论哪种情况,server/models/person.js中的完整模型都是:

In either case, the full model in server/models/person.js is:

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Use native promises.
mongoose.Promise = global.Promise;

// Define the Person schema.
const PersonSchema = new Schema({
  // ...
});

const Person = mongoose.model('Person', PersonSchema);

module.exports = Person;

我有MongoDB 4.2.3(在mongo shell中带有db.version()),npm 6.14.4,mongoose 5.7.5和npm mongodb 3.3.2(带有npm list | grep mongodb).

I have MongoDB 4.2.3 (with db.version() in the mongo shell), npm 6.14.4, mongoose 5.7.5, and npm mongodb 3.3.2 (with npm list | grep mongodb).

为什么MongoDB除了_id之外还需要一个唯一字段来创建集合?

Why does MongoDB require a unique field in addition to _id to create a collection?

推荐答案

我刚刚尝试用几乎相同版本的mongoose和MongoDB复制您上面所述的方案,效果很好,创建了(并保存了)文档模式中firstName字段上没有唯一属性.我不认为您的对象未保存在数据库中的原因是因为缺少唯一属性.

I just tried replicating the scenario you described above on my end with near the same version of mongoose and MongoDB, it worked fine, documents were created(and saved) without the unique property on the firstName field in the schema. I don't think the reason your objects were not saved in the DB is because of the absence of the unique property.

此外,没有唯一属性就没有创建集合的原因是mongoose(或MongoDB本身)不会创建集合,除非您将数据插入到集合中.通过添加唯一属性,MongoDB必须为集合中的该属性创建索引文档,从而向集合中添加数据,这就是为什么似乎仅在添加唯一属性后创建了集合的原因.因此,尽管db.<collectionName>.find({})可能不会返回任何内容,但db.<collectionName>.getIndexes()会给您一些东西.

Also, the reason the collection was not created without the unique property is that mongoose(or MongoDB itself) won't create a collection until you insert data into the collection. By adding the unique property, MongoDB would have to create an index document for that property in the collection consequently adding data to the collection and this is why it seems that the collection was created only after adding the unique property. So while the db.<collectionName>.find({}) might return nothing, db.<collectionName>.getIndexes() would give you something.

这篇关于为什么MongoDB需要`unique:true`来创建一个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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