1

My post schema looks like this.

const Post = new Schema({
  author: String,
  view: Number,
  point: Number,
  title: String,
  images: [Schema.Types.Mixed],
  content: String,
  tags: [String],
  comments: [{ displayName: String, body: String, createdAt: Date }],
  createdAt: {
    type: Date,
    default: Date.now
  },
  editedAt: Date
})

And my query is:

Post.statics.findByTags = function(tags) {
  return this.find({
      tags: { $in: tags }
  }).
  limit(10).
  sort({ createdAt: -1 }).
  exec()
}

What I'm trying to do is match posts which have one of the tags provided by parameter "tags".

ex) if tags equals ["tag1", "tag2"] and

Post1 = { ...some values, tags: ["tag1"]}, Post2 = { ...some values, tags: ["tag1", "tag2"]}

I want to match both posts.

I'm using Postman to test those queries and now I'm getting nothing except an empty array.

halfer
  • 19,824
  • 17
  • 99
  • 186
Gompro
  • 2,247
  • 1
  • 16
  • 26
  • Questions seeking debugging help (**"why isn't this code working?"**) must include the desired behavior, a *specific problem or error and the shortest code necessary* to reproduce it **in the question itself**. Questions without a **clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve) – Neil Lunn Sep 02 '17 at 08:21
  • So what does "MCVE" mean? It means you should be verifying that your collection actually is called "posts" [just as mongoose is expecting](https://stackoverflow.com/questions/14183611/mongoose-always-returning-an-empty-array-nodejs) and you are indeed connecting to the correct database space ( we need to see it to be "verifiable" ) and that your usage of the method shown ( that's called "complete" ) is shown in a way that others can reproduce. Or indeed by following those steps you actually realize what you did wrong. – Neil Lunn Sep 02 '17 at 08:24

1 Answers1

0

I found mistakes that I made.

The query wasn't wrong and what I did wrong was saving "tags" field with JSON like String like "['xxx', 'xxxx']". it seems perfect array but yeah, it is just a string and I couldn't get the result I expected.

so, I added JSON.parse in "createPost" method and it now produces the right result.

// tags should be array type, so parse them
let { tags } = body
tags = JSON.parse(tags)
const { author, title, images, content } = body
Gompro
  • 2,247
  • 1
  • 16
  • 26