findByIdAndUpdate $set does not check for unique? - javascript

I have a schema and specify login is unique is true. When I use findByIdAndUpdate and pass query $set to update an user object, it did not throw back error when login is dup. Does anyone know why and how I should update an object and force schema validation?
Thanks!
// UserSchema.js
var schema = new Schema({
login: {
required: true,
unique: true
},
password: {
index: true,
type: String
}
});
// Update
UserSchema.findByIdAndUpdate('someID', { '$set': { login: 'abc' } }, function (error, user) {
callback(error, user);
});

You simply need to set runValidators to true:
findByIdAndUpdate(req.params.id, {$set: data}, {runValidators: true}, function (err, doc) {
if (err) {
// Handle validation errors
}
})
More here: http://mongoosejs.com/docs/api.html#findOneAndUpdate

Using the shorthand helper methods in Mongoose bypasses validation, so you need to use a 3 step approach:
Find
Edit
Save
For example:
// 1: Find
UserSchema.findById( 'someID',
function (err, user) {
if(!err){
// 2: Edit
user.login = 'abc';
// 3: Save
user.save(function (err, user) {
if (err) {
console.log(err);
return;
}
console.log('User saved: ' + user);
});
}
}
);

Related

Prevent Duplicate Documents in MongoDB?

I'm trying to figure out the best way to prevent duplicate documents from being saved in MongoDB.
Right now my form takes the user_url from the user. The logic is:
Check if the user_url is valid. (dns.lookup)
If user_url is new, save it to the database and return url_ID.
If user_url is old, just return the url_ID.
I think my 2 options are:
var findOneURL = function(user_url, done) {
URL.findOne({
orig_url: user_url
}, (err, data) => {
if (err) {
done(err);
}
done(null, data);
})
}
or
var findEditThenSave = function(user_url, done) {
URL.findById(user_url, (err, data) => {
if (err) {
done(err);
}
data.save((err, data) => {
if (err) {
done(err);
}
done(null, data);
});
})
};
It's not working terribly well at the moment but this is the live version:
https://kindly-fisherman.glitch.me/
EDIT2: I think I got it working properly now. Here's my logic:
Saving to database: dns.lookup -> findByURL -> (If it doesn't exist) -> countURLs -> findAndUpdateURL -> Return what was saved to database.
OR -> (If it exists) -> Return the record.
Retrieving from database: findByID
The best choice is findOneAndUpdate query with upsert and returnNewDocument options
db.collection.findOneAndUpdate({ orig_url: user_url }, { $set: { orig_url: user_url }}, { upsert: true, returnNewDocument: true })
In mongoose
URL.findOneAndUpdate({orig_url: user_url }, { $set: { orig_url: user_url }}, { upsert: true, new: true }, (err, data) => {
if (err) {
done(err);
}
// data will contain your document
done(null, data);
});
upsert option specifies whether to insert document if not found, new (returnNewDocument in mongo's console) - whether to return old or updated document - if false (default is false) you will have null for inserted documents.
Instead of using
db.insert()
you should use
db.update()
and specify
$upsert: true
[here]

Populate Query Options with Async Waterfall

I'm trying mongoose populate query options but i don't know why the query options doesn't work.
I have user schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema(
{
username: { type: String, required: true },
email: { type: String },
name: { type: String },
address: { type: String }
},
{ timestamps: true }
);
module.exports = mongoose.model('User', UserSchema);
and feed schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FeedSchema = new Schema(
{
user: { type: Schema.ObjectId, ref: 'User' },
notes: { type: String, required: true },
trx_date: { type: Date },
status: { type: Boolean, Default: true }
},
{ timestamps: true }
);
FeedSchema.set('toObject', { getters: true });
module.exports = mongoose.model('Feed', FeedSchema);
I want to find all feed by user id, i used async waterfall like the following code:
async.waterfall([
function(callback) {
User
.findOne({ 'username': username })
.exec((err, result) => {
if (result) {
callback(null, result);
} else {
callback(err);
}
});
},
function(userid, callback) {
// find user's feed
Feed
.find({})
// .populate('user', {_id: userid._id}) <== this one also doesn't work
.populate({
path: 'user',
match: { '_id': { $in: userid._id } }
})
.exec(callback);
}
], function(err, docs) {
if (err) {
return next(err);
}
console.log(docs);
});
With above code, i got all feeds, and it seems like the query option do not work at all, did i doing it wrong ?
Any help would be appreciate.
Not sure why you are looking to match "after" population when the value of _id is what is already stored in the "user" property "before" you even populate.
As such it's really just a simple "query" condition to .find() instead:
async.waterfall([
(callback) =>
User.findOne({ 'username': username }).exec(callback),
(user, callback) => {
if (!user) callback(new Error('not found')); // throw here if not found
// find user's feed
Feed
.find({ user: user._id })
.populate('user')
.exec(callback);
}
], function(err, docs) {
if (err) {
return next(err);
}
console.log(docs);
});
Keeping in mind of course that the .findOne() is returning the whole document, so you just want the _id property in the new query. Also note that the "juggling" in the initial waterfall function is not necessary. If there is an error then it will "fast fail" to the end callback, or otherwise pass through the result where it is not. Delate "not found" to the next method instead.
Of course this really is not necessary since "Promises" have been around for some time and you really should be using them:
User.findOne({ "username": username })
.then( user => Feed.find({ "user": user._id }).populate('user') )
.then( feeds => /* do something */ )
.catch(err => /* do something with any error */)
Or indeed using $lookup where you MongoDB supports it:
User.aggregate([
{ "$match": { "username": username } },
{ "$lookup": {
"from": Feed.collection.name,
"localField": "_id",
"foreignField": "user",
"as": "feeds"
}}
]).then( user => /* User with feeds in array /* )
Which is a bit different in output, and you could actually change it to look the same with a bit of manipulation, but this should give you the general idea.
Importantly is generally better to let the server do the join rather than issue multiple requests, which increases latency at the very least.

Can't push a json object into array using javascript and mongodb

I have a problem pushing into my Student model data and its schema looks as below:
var StudentSchema = new Schema({
firstName: {
type: String,
trim: true,
default: ''
//validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: ''
//validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
worksnap: {
user: {
type: Object
},
timeEntries : [],
},
timeEntries : []
});
While my javascript code for pushing items looks like this:
Student.findOne({
'worksnap.user.user_id': item.user_id[0]
})
.populate('user')
.exec(function (err, student) {
if (err) {
throw err;
}
//student.timeEntries.push(item); // this works
student.worksnap.timeEntries.push(item); // this does not work
student.save(function (err) {
if (err) {
//return res.status(400).send({
// message: errorHandler.getErrorMessage(err)
//});
} else {
console.log('item inserted...');
}
});
});
As you can see, if I use timeEntries array outside the worksnap object it works fine, it inserts the item as object into that array... I just don't know why it is not working the same being inside worksnap object.
Is there any other option that I can add json objects into an array type in mongo
Thanks
Use .lean()
Documents returned from queries with the lean option enabled are plain JavaScript objects, not MongooseDocuments. They have no save method, getters/setters or other Mongoose magic applied.
Student.findOne({
'worksnap.user.user_id': item.user_id[0]
})
.populate('user')
.lean()//-----Added!
.exec(function(err, student) {
if (err) {
throw err;
}
//student.timeEntries.push(item); // this works
student.worksnap.timeEntries.push(item); // this does not work
student.save(function(err) {
if (err) {
//return res.status(400).send({
// message: errorHandler.getErrorMessage(err)
//});
} else {
console.log('item inserted...');
}
});
});

Mongoose not saving an updated document to the database

EDIT: This question was asked earlier, but I didn't do a good job of asking it. I've rewritten the question. Thanks in advance for your help!
I'm in the process of writing a simple messaging server for a school project. Among its other functionalities, the server allows the user to update the information stored in their account. When the user does update their account, an authentication token is generated for them. Here's the schema that defines all of that. Note, header and body are parts of the user input:
UserSchema = new Schema({
_id: {type: ObjectId, select: false},
username: {type: String, required: true, index: {unique: true} },
password: {type: String, required: true, select: false},
email: {type: String},
token: {type: String, select: false}
}, {
autoIndex: false
});
UserSchema.pre("save", function(next) {
// Create a new token for the user
var self = this;
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) {
next(err);
} else {
crypto.randomBytes(256, function(err, bytes) {
if (err) {
next(err);
} else {
bytes = bytes.toString("hex");
bcrypt.hash((new Date() + bytes), salt, function(err, tokenHash) {
if (err) {
next(err);
} else {
self.token = tokenHash;
next();
}
});
}
});
}
});
});
UserSchema.pre("save", function(next) {
// Hash the password before saving
var self = this;
if (!self.isModified("password")) {
next();
} else {
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) {
next(err);
} else {
bcrypt.hash(self.password, salt, function(err, passwordHash) {
if (err) {
next(err);
} else {
self.password = passwordHash;
next();
}
});
}
});
}
});
I'm running into an issue when updating a particular user. Because I want to use the Model middleware, the way I'm updating a user is by using Model#findOne() followed by Model#save(). Here's the code I have to do that:
// Make sure user provided all necessary information.
if (!header.token) {
return callback(new errors.MissingHeaderDataError("Missing 'token' parameter in the header."));
} else {
// Update the user account based on what's in the envelope's body.
User.findOne({"token": header.token}, "+token +password", function (err, user) {
if (err) {
return callback(err);
} else {
// Get a list of all parameters the user wants to change.
var paramsToChange = Object.keys(body);
// Now update the parameters
paramsToChange.forEach(function(param) {
user[param] = body[param];
});
console.log("Updated user:");
console.dir(user);
user.save(function(err, user) {
if (err) {
return callback(err);
} else {
console.log("Returned user:");
console.dir(user);
User.find({}, "+token +password", function(err, foundUser) {
if (err) {
throw err;
} else {
console.log(JSON.stringify(foundUser));
}
});
callback(null, new SuccessEnvelope(user));
}
});
}
});
}
When I run my tests and come to the last bit of code (after save() is returned), I get this output:
Updated user:
{ token: '$2a$10$5VWWqjJ52aGbS4xc6NDKjuGPv8brX7pRmwiKyYjP8VHoTKCtYZiTu',
username: 'jim_bob',
password: '$2a$10$ue08HUsunzzzcbZURzXF7uaH1dZxF3SwkwadC6D1JsIC9xAUhTbCC',
email: 'joe_bob#email.com',
__v: 0 }
Returned user:
{ token: '$2a$10$fRwED..7fFFhN46Vn.ZJW..xYql5t5P39LHddjFS4kl/pmhwfT.tO',
username: 'jim_bob',
password: '$2a$10$ue08HUsunzzzcbZURzXF7uaH1dZxF3SwkwadC6D1JsIC9xAUhTbCC',
email: 'joe_bob#email.com',
__v: 0 }
[{"token":"$2a$10$5VWWqjJ52aGbS4xc6NDKjuGPv8brX7pRmwiKyYjP8VHoTKCtYZiTu","username":"joe_bob","password":"$2a$10$ue08HUsunzzzcbZURzXF7uaH1dZ
xF3SwkwadC6D1JsIC9xAUhTbCC","email":"joe_bob#email.com","__v":0}]
As you can see, the document is not properly saved to the database, as the previous data is still there. My question is: why? Why is the user not being updated when calling save? I think I'm doing everything properly, but obviously I'm not. Any help with this would be great since I'm going mad!
Apparently, in order to save a document to the database, it needs an _id. Kinda silly that Mongoose doesn't give an error when it doesn't find a document. Alas...
I updated my code to reflect the change:
// Make sure user provided all necessary information.
if (!header.token) {
return callback(new errors.MissingHeaderDataError("Missing 'token' parameter in the header."));
} else {
// Update the user account based on what's in the envelope's body.
User.findOne({"token": header.token}, "+_id +token +password", function (err, user) {
if (err) {
return callback(err);
} else {
console.log("Found user:");
console.dir(user);
// Get a list of all parameters the user wants to change.
var paramsToChange = Object.keys(body);
// Now update the parameters
paramsToChange.forEach(function(param) {
user[param] = body[param];
});
console.log("Updated user:");
console.dir(user);
user.save(function(err, user, numberTouched) {
if (err) {
return callback(err);
} else {
console.log("Returned user:");
console.dir(user);
console.log(numberTouched);
User.find({}, "+token +password", function(err, foundUser) {
if (err) {
throw err;
} else {
console.dir(foundUser);
}
});
callback(null, new SuccessEnvelope(user));
}
});
}
});
}

Mongoose: Find, modify, save

I have a Mongoose User model:
var User = mongoose.model('Users',
mongoose.Schema({
username: 'string',
password: 'string',
rights: 'string'
})
);
I want to find one instance of the User model, modify it's properties, and save the changes. This is what I have tried (it's wrong!):
User.find({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
What is the syntax to find, modify and save an instance of the User model?
The user parameter of your callback is an array with find. Use findOne instead of find when querying for a single instance.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:
User.update({username: oldUsername}, {
username: newUser.username,
password: newUser.password,
rights: newUser.rights
}, function(err, numberAffected, rawResponse) {
//handle it
})
findOne, modify fields & save
User.findOne({username: oldUsername})
.then(user => {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.markModified('username');
user.markModified('password');
user.markModified('rights');
user.save(err => console.log(err));
});
OR findOneAndUpdate
User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
});
Also see updateOne
I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified it worked.
User.findOne({username: oldUsername}, function (err, user) {
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.markModified(username)
user.markModified(password)
user.markModified(rights)
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
tell mongoose about the change with doc.markModified('pathToYourDate') before saving.
If you want to use find, like I would for any validation you want to do on the client side.
find returns an ARRAY of objects
findOne returns only an object
Adding user = user[0] made the save method work for me.
Here is where you put it.
User.find({username: oldUsername}, function (err, user) {
user = user[0];
user.username = newUser.username;
user.password = newUser.password;
user.rights = newUser.rights;
user.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
You could also write it a little more cleaner using updateOne & $set, plus async/await.
const updateUser = async (newUser) => {
try {
await User.updateOne({ username: oldUsername }, {
$set: {
username: newUser.username,
password: newUser.password,
rights: newUser.rights
}
})
} catch (err) {
console.log(err)
}
}
Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.
Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate

Categories

Resources