Search code examples
node.jsmongodbnode-mongodb-native

node-mongodb-native remove by DBRef $id (dot issue)


I have 2 collections in my mongodb database: users and posts. And in posts collection I have DBRef field like this:

user : DBRef('users', ObjectId('...'), null)

When I'm going to remove some post by user id, I do the following:

db.posts.remove({ 'user.$id' : ObjectId('...') })

And it works great, but not from node-mongodb-native. From node-mongodb-native I'm getting following error while doing this request:

key must not contain '.'

Can anyoune see that? Thank you for your help and explanations if I'm wrong in something.

Update

find requests by DBRef $id work fine!

Node.js code:

var mongodb = require('mongodb')
  , nconf = require('nconf')
  , MongoClient = mongodb.MongoClient;

MongoClient.connect(nconf.get('db:connectionString'), function(mongoConnectionError, db) {
  if (mongoConnectionError) throw mongoConnectionError;

  db
    .collection('posts')
    .remove({ 'user.$id' : new mongodb.ObjectID('...') }, {}, function(err, removedItems) {
      if (err) { throw err; }

      console.log('Removed items: ' + removedItems);
    });
 });

Solution

  • I've used a similar model, but my post was from ONE user, making it simply:

    db.posts.remove({'user_id' : ObjectID('...') });
    

    In this case, it looks more like the collection posts has an array user with id in it.

    If I'm not mistaken, you should use the $ in the user array to do something to an element in an array once you've matched.

    If your purpose is removing the entire post, simply remove it by matching the id in the users array:

    db.posts.remove({user:{$in:ObjectID('...'}});
    

    Otherwise, $pull, as said above.