Sails.js & Waterline ORM unset key MongoDB
What method is used to revoke a key in MongoDB using Waterline ORM?
Consider the following document:
{
name : 'brian',
age : 29
}
Getting the user is not a problem:
var users = Users.findOne({ name : 'brian' }).exec(cb);
I wish the age would just disappear. I tried the following:
user.age = undefined;
user.save();
user.age = null;
user.save();
delete user.age;
user.save();
No, it seems to work. # 1 sets it to null, # 2 sets it to null, # 3 leaves the original value.
Thank.
source to share
Waterline is an ORM designed to support a wide variety of datastores, so it doesn't support MongoDB-specific methods. You can always get access to the underlying driver using MongoDB and then do whatever you want (see. Documentation on the driver unit MongoDB for methods available): .native()
User.native(function(err, collection) {
collection.findAndModify(
{name: 'brian'},
{$unset: {age: true}},
function (err, object) {
// Continue...
}
);
})
source to share
Mongodb server version 3.2.9. Sails version is 0.12.6. Node version 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"});
}
);
});
source to share
The currently accepted answer does not work with current versions of Sails and Mongo. In Sails 1.1.0 ( sails-mongo
1.0.1), as of mongo 4.0, where User
is the Sails model name, to reset a field email
:
const ObjectId = require('mongodb').ObjectID
const mongo = User.getDatastore().manager
const userCollection = mongo.collection(User.tableName)
await userCollection.update(
{_id: ObjectId(someUserIdString)},
{$unset: {email: ""}},
)
source to share