5

What method is used to unset a key in MongoDB with Waterline ORM?

Consider the following document:

{
    name : 'brian',
    age : 29
}

Getting the user is no problem:

var users = Users.findOne({ name : 'brian' }).exec(cb);

I would like age to simply go away. I've tried the following to accomplish this:

user.age = undefined;
user.save();

user.age = null;
user.save();

delete user.age;
user.save();

None seem to work. #1 sets it to null, #2 sets it to null, #3 leaves the original value.

Thanks.

Stennie
  • 63,885
  • 14
  • 149
  • 175
brian
  • 2,745
  • 2
  • 17
  • 33
  • I don't think it's supported (since Waterline is generic and $unset is adapter-specific). Is there a particular reason you need this vs null? – Xinzz Aug 18 '14 at 20:38
  • @Xinzz, no, I suppose not. I guess the only reason would be readability directly in the database to show only what is set (null or not) and what simply just doesn't belong there. – brian Aug 18 '14 at 20:58

3 Answers3

6

Waterline is an ORM meant to support a wide range of datastores, so it doesn't support methods that are particular to just MongoDB. You can always access the underlying MongoDB driver using the .native() method, then do anything you want (see the MongoDB node driver docs for available methods):

User.native(function(err, collection) {

    collection.findAndModify(
        {name: 'brian'}, 
        {$unset: {age: true}}, 
        function (err, object) {
           // Continue...
        }
    );
})
Pistos
  • 23,070
  • 14
  • 64
  • 77
sgress454
  • 24,870
  • 4
  • 74
  • 92
0

Mongodb server version 3.2.9. Sails version is 0.12.6. Node version is 0.12.4

Policies.native(function(err, collection) {
   var ObjectID = require('mongodb').ObjectID;
   collection.update(
      {"_id": new ObjectID(req.param('id'))},
      {$unset: {defaultSchema: ""}},
      function (err, object) {
         if(err) return res.badRequest(err);
         res.ok({"message":"Ok"});
      }
   );
});
1nstinct
  • 1,745
  • 1
  • 26
  • 30
0

The currently accepted answer doesn't work with the current versions of Sails and Mongo. In Sails 1.1.0 (sails-mongo 1.0.1), with mongo 4.0, where User is the name of a Sails model, to unset the email field:

const ObjectId = require('mongodb').ObjectID
const mongo = User.getDatastore().manager
const userCollection = mongo.collection(User.tableName)

await userCollection.update(
  {_id: ObjectId(someUserIdString)},
  {$unset: {email: ""}},
)
Pistos
  • 23,070
  • 14
  • 64
  • 77