randomuser1 randomuser1 - 1 year ago 68
Node.js Question

How can I modify my mongodb query so that the results do not contain specific values stored in an array?

I'm using

and defined a model for a comment section in my app:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CommentSchema = new Schema({
my_username: {type: String, required: true},
text_content: {type: String},
hashtags: {type: [String]},
photo_content: {type: String},
created_at: {type: Date, default: Date.now},
updated_at: {type: Date, default: Date.now}

Now when I'm downloading all comments that belongs to specific timeframe and contains hashtags, I have:

var hashtagsInput = req.body.hashtags;
var query= {};

query.$and = [];

if(startDate != undefined && endDate != undefined) {
var startDate = new Date(req.param('startDate'));
var endDate = new Date(req.param('endDate'));
query.$and.push({"created_at":{$gte: startDate}});
query.$and.push({"created_at":{$lte: endDate}});

if (hashtagsInput != undefined) {
var hashtags = hashtagsInput.split(",");
query.$and.push({"hashtags":{$in: hashtags}});

Now I'm trying to add another case to the query - besides an array of hashtags I'm passing array of blocked users:

var blockedUsers = req.body.blockedUsers;

I want to avoid every comment that has an author equal to any of the entries in blockedUsers. so basically I want to have
not in
query. Can you give me a hint of how to construct this additional condition in my query?

rsp rsp
Answer Source

It seems like this should do the trick:

if (blockedUsers) {
  query.$and.push({"my_username": {$not: {$in: blockedUsers}}});

or, even better:

if (blockedUsers) {
  query.$and.push({"my_username": {$nin: blockedUsers}});

Or possibly you need to split it on commas like you do with hashtags - you didn't specify how you pass the blocked users:

var blockedUsers = req.body.blockedUsers;
if (blockedUsers) {
  var blocked = blockedUsers.split(',');
  query.$and.push({"my_username": {$nin: blocked}});

See: https://docs.mongodb.com/manual/reference/operator/query/nin/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download