简体   繁体   中英

Return record if matches exact value using mongodb

model.js

import mongoose from 'mongoose';
const { Schema, Types } = mongoose;

const participants = {
  user_id: Types.ObjectId(),
  isAdmin: Boolean
}

const groupSchema = new Schema({
  id: Types.ObjectId(), // String is shorthand for {type: String}
  name: String,
  users: [participants]
});

export const Group = mongoose.model('Group', groupSchema);

query.js

 export const checkUser = async(groupprops) => {
  await return group.findOne({'participants.user_id': { $all: groupprops } }).exec();
}; // groupprops is array of user_id = ['123', '456'] like this

I want to filter array if the same exact value matches record it must return that only else it must not return record like if I have 3 users of id [123, 456, 789] and I search for users [123, 456] then it must not return any record until I did not enter record that matches exact. I am getting issue as it only checks of [123, 456] exist then it matches the record ignore other values but it must exact matches the user_id

You can use aggregation operator $setEquals to check both the array is equals,

return await group.findOne({
  $expr: {
    $setEquals: ["$users.user_id", groupprops]
  }
}).exec();

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM