0

I have a model which stores Object IDs from another model. Now I need to find inside that model which contains specific ids the other model.

My Schema is : I have a model with a field containing object ids. like..

const SpiceSchema = new mongoose.Schema({
  createdat: {
    type: Date,
    required: true,
    default: Date.now,
  },
  name: {
    type: String,
    required: true,
  },
  image: {
    type: String,
  },
  description: {
    type: String,
  },
  blends: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'blend',
  }],
  flavors: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'flavor',
  }],
  ingredients: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'ingredient',
  }],
  regions: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'region',
  }],
});

Now the document looks like this..

{ blends: [ 5cf296751771e6157cc2b257, 5cf296f1c61d6739b0903ef5 ],
   flavors: [ 5cf2b268acac9e261459ea3a ],
   ingredients: [ 5cf2b281acac9e261459ea3b ],
   regions: [],
   _id: 5cf4162d95aa7d28e0c4e324,
   name: 'themeal',
   description: 'sldkjf ldskjflksdj f\r\nlorem salute saloni',
   createdat: 2019-06-02T18:32:13.270Z,
   __v: 0,
   image: '5cf4162d95aa7d28e0c4e324.jpg' } ]

I have an array of blends comming in from front-end like this..

query.blends: [ '5cf2956b1771e6157cc2b256', '5cf296751771e6157cc2b257' ]

I need to find all documents inside spice schema which contains these two blends..

Currently I'm trying to achieve this by doing:

const spicesQuery = Spice.find();
spicesQuery.where({blends: {$in: query.blends}});
const spices = spicesQuery.sort({name: 1}).exec();
console.log(spices);

I get all the spices in the model.. Not just the one's which have these two blends..

1 Answer 1

1

use $all

spicesQuery.where({blends: {$all: query.blends}});
const spices = await spicesQuery.sort({name: 1}).exec();
Sign up to request clarification or add additional context in comments.

2 Comments

This did the job... Thank you
You're welcome, you could accept the answer to close the question.

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.