Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose aggregate not support writeConcern

I'm trying to count how many notifications are unread for a given user.

That said, vía aggregate, I've done the next code in console that output the expected result:

db.getCollection('users').aggregate([
  { $match: { _id: ObjectId("5847f61a825d024ac9e3d08c")}},
  { $unwind: '$notifications'},
  { $match: {'notifications.read': {$eq: 0}}},
  { $group: { _id: '$_id', notifications: {$push: '$notifications._id'}}}])

which outputs:

{
   "_id" : ObjectId("5847f61a825d024ac9e3d08c"),
   "notifications" : [ 
      ObjectId("5847fefb708b3b4c2cf9e8fe"), 
      ObjectId("5847fefe708b3b4c2cf9e900")
   ]
}

So I'm trying to do the same with nodeJS and mongoose, so I have a model and a static method which is exactly the same as what I have in my last query:

var UserSchema = new mongoose.Schema({
  nickname: { type: String, trim: true},
  username: { type: String, trim: true },
  notifications: [{
    a: {
      _id: { type: mongoose.Schema.Types.ObjectId, ref: 'x' },
      x: { type: mongoose.Schema.Types.ObjectId, ref: 'y' }
    },
    b: {
      _id: { type: mongoose.Schema.Types.ObjectId, ref: 'y' },
      x: { type: mongoose.Schema.Types.ObjectId, ref: 'y' }
    },
    read: { type: Number, default: 0 }, // 0 - Unread, 1 - read
    ts: { type: Date, default: Date.now }
  }]
}, { timestamps: { createdAt: 'created_at' } });


UserSchema.statics.getCountNotifications = function (user_id) {
  return new Promise(function (resolve, reject) {
    mongoose.model('User', UserSchema).aggregate([
      { $match: { _id: mongoose.Types.ObjectId(user_id)}},
      { $unwind: '$notifications'},
      { $match: {'notifications.read': {$eq: 0}}},
      { $group: { _id: '$_id', notifications: {$push: '$notifications._id'}}}], function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

Unfortunatelly, that outputs me the next error: MongoError: Command does not support writeConcern. In fact, checking the logs this is the output:

Unhandled rejection MongoError: Command does not support writeConcern
    at Function.MongoError.create (/Users/Project/api/node_modules/mongodb-core/lib/error.js:31:11)
    at /Users/Project/api/node_modules/mongodb-core/lib/connection/pool.js:462:72
    at authenticateStragglers (/Users/Project/api/node_modules/mongodb-core/lib/connection/pool.js:410:16)
    at .messageHandler (/Users/Project/api/node_modules/mongodb-core/lib/connection/pool.js:444:5)
    at Socket.<anonymous> (/Users/Project/api/node_modules/mongodb-core/lib/connection/connection.js:306:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:172:18)
    at Socket.Readable.push (_stream_readable.js:130:10)
    at TCP.onread (net.js:542:20)
From previous event:
    at Function.UserSchema.statics.getCountNotifications (/Users/Project/api/models/user.js:301:10)
    at /Users/Project/api/routes.js:563:8
    at Layer.handle [as handle_request] (/Users/Project/api/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/Project/api/node_modules/express/lib/router/route.js:131:13)
    at /Users/Project/api/models/user.js:179:7
    at JwtStrategy.strategy.success (/Users/Project/api/node_modules/passport/lib/middleware/authenticate.js:201:18)
    at verified (/Users/Project/api/node_modules/passport-jwt/lib/strategy.js:102:33)
    at /Users/Project/api/app.js:62:7
    at Query.<anonymous> (/Users/Project/api/node_modules/mongoose/lib/model.js:3336:16)
    at /Users/Project/api/node_modules/kareem/index.js:259:21
    at /Users/Project/api/node_modules/kareem/index.js:127:16
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

Any help with this?

Thanks in advice.

like image 371
DevStarlight Avatar asked May 07 '26 05:05

DevStarlight


1 Answers

After digging into the issue, the problem was the version of my mongoose. After updating into 4.7.1 and following mongoose doc, it works like a charm. Here bellow I leave the final version of my code:

this.aggregate({ $match: { _id: mongoose.Types.ObjectId(user_id)}})
   .unwind('notifications')
   .match({ 'notifications.read': { $eq: 0 } })
   .group({ _id: '$_id', notifications: { $push: '$notifications._id'} })
   .exec();
like image 158
DevStarlight Avatar answered May 09 '26 00:05

DevStarlight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!