skip to Main Content

I was working with the MongoDB Atlas Server…
and encountered this error…
What does it mean…?
Can someone explain in simple words plz…

This was the query i was trying…

db.posts.find({}, {title: 1, date: 0})

The structure of the posts in database is as follows:

[
  {
    _id: ObjectId("63739044de169f6d0h2e6a3d"),
    title: 'Post 2',
    body: 'a news post',
    category: 'News',
    likes: 1,
    tags: [ 'news', 'events' ],
    date: 'Tue Nov 15 2022 18:53:24 GMT+0530 (India Standard Time)'
  },
  {
    _id: ObjectId("63739271de179f5d0e31e5b2"),
    title: 'Post 1',
    body: 'hey there, hemant here',
    category: 'random',
    likes: 1,
    tags: [ 'random', 'events' ],
    date: 'Tue Nov 15 2022 18:41:24 GMT+0530 (India Standard Time)'
  }
]

But I got an error which says…

MongoServerError: Cannot do exclusion on field date in inclusion projection

I was trying to get all the document objects excluding the date parameter and including the title parameter but got an error…

2

Answers


  1. According to the documentation, first argument in find is filter and second is projection. projection allows you to specify fields to return._id is the only field which you need to explicitly exclude in the projection. For all other fields you just need to state the inclusion. You will have to follow the below format.

    db.posts.find({}, {title: 1, body:1, category:1, likes:1, tags:1})
    
    Login or Signup to reply.
  2. Another possibility is that

    Inside the ‘posts’ mongoose schema,
    if we set the date key like this

    date: {
      type: string,
      select: true
    }
    

    the select:true always returns the date key in all find queries

    and passing {date:0} in projection or dot_select(.select) object will return this error:

    Cannot do exclusion on field date in inclusion projection

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search