3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[mongoose] サブドキュメントの配列要素に_idを作らないようにする。

Last updated at Posted at 2019-06-19

前略

Node.jsでMongoDBを扱えるパッケージであるmongooseの記事。

mongooseでデータを登録した際に
いらないのに_idプロパティが作られてしまうことがあったので
その回避方法。

解決したいこと

登録されたデータの構造
{ 
  _id: 11,
  title: 'sample',
  data:[ 
    { _id: 5d0a6368ac03fe1aabd7c33f, field: 'value1' },
    { _id: 5d0a6368ac03fe1aabd7c33e, field: 'value2' },
    { _id: 5d0a6368ac03fe1aabd7c33d, field: 'value3' } 
  ],
}

dataに含まれるオブジェクトに_idプロパティが作られないようにしたい:

登録したいデータの構造
{ 
  _id: 11,
  title: 'sample',
  data:[ 
    { field: 'value1' },
    { field: 'value2' },
    { field: 'value3' } 
  ],
}

解決方法

mongooseでは登録するデータの構造を
mongoose.Schemaを使って定義する。

サブドキュメントの配列要素に_idプロパティを作りたくない場合は
下記のようにスキーマを定義してあげればよい。

_idを作らないようにするスキーマの定義
const mongoose = require('mongoose');

// サブスキーマを定義する。
var subSchema = mongoose.Schema({
  field: {
    type: String,
    required:true,
  }
}, {_id:false}) // ← ここがポイント、これで_idが作られなくなる

const schema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  data: {
    type:[subSchema], // 定義したサブスキーマを指定する。
    default:[],
    required: true,
  },
});

ちなみに普通のスキーマはこんな感じで定義すると思うが
この場合はサブドキュメントの配列要素に_idが作られてしまう。

このSchemaはダメな例(_idが作られてしまうパターン)
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  data: {
    type:[
      {
        field:String
      }
    ],
    default:[],
    required: true,
  },
});
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?