When I query monodb shell, I AM able to update the document.
This is the mongodb command I use:
db.users.update({name:"bob"}, {$set: {email:"newEmail#gmail.com} })
But when I try to update it with mongoose, it doesn't work.
What am I missing??
This is the code in mongoose:
// Create the users schema
var userSchema = mongoose.Schema({
name: String,
email: String
}, {collection: "users"});
// Create a model
var userModel = mongoose.model("userModel", userSchema);
// Update a document
userModel.update({name:"bob"}, {$set: {email:"newEmail#gmail.com"}} );
You should wait for the callback to see if the operation was succesful or not
userModel.update({ name: "bob" },
{$set: { email:"newEmail#gmail.com" }},
function (err, user) {
if (err) return handleError(err);
res.send(user);
});
The mongoose is working asynchronously, you should wait for the response in the callback. There is also a synchrone way to do that but With node is not recommended you will block the stack.
You can use this if you don't need the result in callback
userModel.update({name:"bob"}, {$set: {email:"newEmail#gmail.com"}}).exec();
Related
I am trying to update one element of snippets in my mongoose schema.
My Mongoose schema.
const Schema = new mongoose.Schema({
// ...
createdAt: Date,
snippets: {} // here I push ['string..', ['array of strings..']]
})
Here's a view of snippets in Compass.
Problem with the code below is that it completely erases other elements stored, other than that it works. Unable to specify that I want to update snippets[0], not entire thing..?
User.findOneAndUpdate({ username: req.session.user.username },
{ $set: { snippets: [snippet] } }, callback)
Tried using findOne andsave but it wouldn't update the db.
const snippet = [req.body.code, [req.body.tags]]
User.findOne({ username: req.session.user.username }, function (err, fetchedUser) {
if (err) console.log(err)
fetchedUser.snippets[req.params.id] = snippet // should be set to new snippet?
fetchedUser.save(function (err, updatedUser) {
if (err) console.log(err)
console.log('edited')
// ...
})
})
Any suggestions?
I thought I tried this earlier, but apparantly not.
Using fetchedUser.markModified('snippets') solved my issue with findOne/save not actually saving to DB.
I have a schema that is defined like
var UserSchema = mongoose.Schema({
user: {
ipAddress: String,
pollIDs: [{
id: String
}]
}
});
var User = module.exports = mongoose.model('User', UserSchema);
What I want to create is a route that checks the requests ip address, see if it exists in the database, if it doesn't create a new document with the ipAddress property set accordingly and the current req.body.poll_id to be an element in the pollIDs array.
However, if there is a document with that ip address I want the req.body.poll_id to be pushed into the pollIDs array.
I would demonstrate my first attempt, but I know that I've messed up the parameters on the findOneAndUpdate call.
Should be as simple as:
User.findOneAndUpdate(
{'user.ipAddress': req.body.ipAddress},
{$push: {'user.pollIDs': {id: req.body.poll_id}}},
{upsert: true, new: true},
(err, doc) => {...});
The upsert will take the query object and apply the update operation to it in the case where it needs to insert a new document.
If I add new fields directly to my MongoDB database and I forget to add them to my Mongoose schema, how can I alert myself to the problem without it failing silently.
The following example shows that all fields are returned from a query (regardless of the schema) but undefined if you access the key.
var mongoose = require('mongoose');
var user_conn = mongoose.createConnection('mongodb://db/user');
var userSchema = mongoose.Schema({
email: String,
// location: String,
admin: Boolean
});
var User = user_conn.model('User', userSchema);
User.findOne({email: 'foo#bar.com.au'}, function (err, doc) {
if (err) return console.log(err);
console.log(doc);
console.log(doc.email);
console.log(doc.location);
});
Result:
{ _id: 57ce17800c6b25d4139d1f95,
email: 'foo#bar.com.au',
location: 'Australia',
admin: true,
__v: 0 } // <-- console.log(doc);
foo#bar.com.au // <-- console.log(doc.email);
undefined // <-- console.log(doc.location);
I could read each doc key and throw an error if undefined, but is this the only way?
Versions
Node.js: 6.5.0
Mongoose: 4.6.0
You can set strict to false on the schema so it will save all properties even if they are not in schema:
var userSchema = mongoose.Schema({
email: String,
admin: Boolean
}, {strict: false});
http://mongoosejs.com/docs/guide.html#strict
In order to get a property which is not in schema you need to use doc.toObject() and use the returned object, or to use doc.get('location')
Following on from Amiram's answer. I now use lean() to get the object during a query but when I need to update or save it still looks up the schema.
User.findOne({email: 'foo#bar.com.au'}).lean().exec(function (err, doc) {
console.log(doc);
console.log(doc.email);
console.log(doc.location);
});
I just noticed that when i update my schema definition and add a field, for instance "name: String" and then try to use
People.update( { _id: user_id }, { $set: { name: 'something' } } )
mongoose won't update my property.
I keep getting nModified: 0 on the response.
The only way i found to fix it, is to Drop the collection and then the new documents will work perfectly.
Am i missing something? Does mongoose somehow "caches" the schema of a collection on mongodb itself and then needs a "drop" in order to "reload" the properties?
I think findbyidandupdate will do the task for you. Try with this link
Mongoose - findByIdAndUpdate - doesn't work with req.body
Can you please share your People model and also please use callback with update.
see below and works fine..
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = mongoose.model('User', { email: String, name: String });
//First added only email and used save to save the document.
//var user = new User({ email: 'john.due#example.com' });
User.update({ _id: '55fbbb268e7307dc0bf9ae92' }, { $set: { name: 'John Due' }}, function(err, result) {
if(err) throw err;
console.log(result)
});
Stop your node app and restart the app. It should work.
Let's suppose I have a schema like this:
var Person = new Schema({
name: String
});
var Assignment = new Schema({
name: String,
person: ObjectID
});
If I delete a person, there can still be orphaned assignments left that reference a person that does not exist, which creates extraneous clutter in the database.
Is there a simple way to ensure that when a person is deleted, all corresponding references to that person will also be deleted?
You can add your own 'remove' Mongoose middleware on the Person schema to remove that person from all other documents that reference it. In your middleware function, this is the Person document that's being removed.
Person.pre('remove', function(next) {
// Remove all the assignment docs that reference the removed person.
this.model('Assignment').remove({ person: this._id }, next);
});
If by "simple" you mean "built-in", then no. MongoDB is not a relational database after all. You need to implement your own cleaning mechanism.
The remove() method is deprecated.
So using 'remove' in your Mongoose middleware is probably not best practice anymore.
Mongoose has created updates to provide hooks for deleteMany() and deleteOne().
You can those instead.
Person.pre('deleteMany', function(next) {
var person = this;
person.model('Assignment').deleteOne({ person: person._id }, next);
});
In case if anyone looking for the pre hook but for deleteOne and deleteMany functions this is a solution that works for me:
const mongoose = require('mongoose');
...
const PersonSchema = new mongoose.Schema({
name: {type: String},
assignments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Assignment'}]
});
mongoose.model('Person', PersonSchema);
....
const AssignmentSchema = new mongoose.Schema({
name: {type: String},
person: {type: mongoose.Schema.Types.ObjectId, ref: 'Person'}
});
mongoose.model('Assignment', AssignmentSchema)
...
PersonSchema.pre('deleteOne', function (next) {
const personId = this.getQuery()["_id"];
mongoose.model("Assignment").deleteMany({'person': personId}, function (err, result) {
if (err) {
console.log(`[error] ${err}`);
next(err);
} else {
console.log('success');
next();
}
});
});
Invoking deleteOne function somewhere in service:
try {
const deleted = await Person.deleteOne({_id: id});
} catch(e) {
console.error(`[error] ${e}`);
throw Error('Error occurred while deleting Person');
}
You can leave the document as is, even when the referenced person document is deleted. Mongodb clears references which point to non-existing documents, this doesn't happen immediately after deleting the referenced document. Instead, when you perform action on the document, e.g., update. Moreover, even if you query the database before the references are cleared, the return is empty, instead of null value.
Second option is to use $unset operator as shown below.
{ $unset: { person: "<person id>"} }
Note the use of person id to represent the value of the reference in the query.
you can use soft delete. Do not delete person from Person Collection instead use isDelete boolean flag to true.
Use $pull. Suppose you have a structure like this.
Stuff Collection:
_id: ObjectId('63dd23c633c17a718c4c5db7')
item: "Item 1"
user: ObjectID('63de669153bc12ecb9081b9e')
User collection:
_id: ObjectId('63de669153bc12ecb9081b9e')
stuff: array[ObjectId('63dd23c633c17a718c4c5db7'), ObjectId('63de3a69715ec134e161b0ea')]
Then after you remove the stuff:
const stuff = Stuff.findById(req.params.id)
const user = User.findById(req.params.id)
await stuff.remove()
// here you can use $pull to update
await user.updateOne({
$pull: {
stuff: stuff.id
}
})
you can simply call the model that needs to be deleted and delete that document like this:
PS: This answer is not specific to the question schema.
const Profiles = require('./profile');
userModal.pre('deleteOne', function (next) {
const userId = this.getQuery()['_id'];
try {
Profiles.deleteOne({ user: userId }, next);
} catch (err) {
next(err);
}
});
// in user delete route
exports.deleteParticularUser = async (req, res, next) => {
try {
await User.deleteOne({
_id: req.params.id,
});
return res.status(200).json('user deleted');
} catch (error) {
console.log(`error`, error);
return next(error);
}
};