Mongoose: Remove `_id` from document json representation

Created on 15 Sep 2017  路  1Comment  路  Source: Automattic/mongoose

feaure/bug

When using sub documents in the schema and calling toJSON - it seems there is no way to remove _id fields from it.

Example

const ArticleSchema = new Schema({
  title: {
    type: String,
    default: 'New article',
    trim: true
  },
  slug: String,
  types: [{
    name: String,
    slug: String
  }]
}, { id: false });

  // convert mongoose document to JSON
  const types = req.article.toJSON().types;

  res.json(types); // types will have name, slug and _id fields

node.js 6.10.10, mongoose 4.11.3, MongoDB 2.6.10

Most helpful comment

types: [new Schema({
    name: String,
    slug: String
  }, { _id: false, id: false })]

>All comments

types: [new Schema({
    name: String,
    slug: String
  }, { _id: false, id: false })]
Was this page helpful?
0 / 5 - 0 ratings