0

I try to find refs I've stored in my db by sending an array of object to my API. In the array I send there are 4 objects. 2 of them are already stored, 2 of them are new.

Here is what is stored in my DB:

[
  {
    ref: 'xxx14-010-S',
    colorWay: 'Black',
  },
  {
    ref: 'xxx18-050-S',
    colorWay: 'Black',
  },
...
]

My req.body look like this :

[
  {
    ref: 'xxx14-010-S',
    colorWay: 'Black',
  },
  {
    ref: 'xxx18-050-S',
    colorWay: 'Black',
  },
  {
    ref: 'xxx20-010-S',
    colorWay: 'Black',
  },
  {
    ref: 'xx324-010-S',
    colorWay: 'Black',
  }
]

And here is the code in my express router:

router.post("/api/v1/lineList", async (req, res, next) => {
  try {
    const existingRefs = await LineList.find({ref: {$in: req.body.ref}});
    res.send(existingRefs);
  } catch (err) {
    next(err);
  }
});

This returns an empty array where I expect to find the 2 stored objects. How shall I proceed ? Is there a way to get the 2 found objects and also be notified that the 2 other object where not in the db ?

Thanks a lot !

EDIT: Here is the model:

const lineListSchema = new mongoose.Schema({
  ref: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    uppercase: true,
  },
  styleName: {
    type: String,
    required: true,
    trim: true,
    uppercase: true,
  },
  colorWay: {
    type: String,
    required: true,
    trim: true,
    uppercase: true,
  },
 ...
  createdAt: {
    type: Date,
    default: Date.now,
    expires: 3600,
  },
});

1 Answer 1

1

$in syntax is:

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

So you need to pass an array like this:

await LineList.find({ ref: { $in: req.body.map(val => val.ref) } });
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, this make sens but I still get an empty array in the console.log
I added it to my post
Biog Sorry I've just found my db was droped... your solution work !!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.