Mongoose won't update new field after updating schema declaration - node.js

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.

Related

Update element in Array of Mongoose schema

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.

How to get latest object of array from users in Mongodb

my mongodb structure
//First user
_id:ObjectId("12345")
name:"prudhvi"
authors:Array
0:Object
authorId:"77777"
authortitle:"medicine"
1:Object
authorId:"66666"
authortitle:"Hospital"
//second user
_id:ObjectId("67890")
name:"venkat"
authors:Array
0:Object
authorId:"55555"
authortitle:"Doctor"
1:Object
authorId:"44444"
authortitle:"Nurse"
Can someone please help here i have two users, On that i need to get only the latest object of authors array. Here my latest Object is 1:Object, If in case one more is added, I need to get 2:Object of data of all users.
I tried like this but i am getting all objects of authors array, But i need to get latest object
userRouter.post('/getAuthors', function (req, res) {
Collections.user.find(req.body.user, function (err, result) {
if (err) res.status(500).send("There was a problem finding the user");
if (result.length > 0) {
res.status(200).send(result[0].authors);
}
}).select({ "authors": 1 });
});
Try using this
Collections.user.find().limit(1).sort({$natural:-1})
Take a look at $natural and cursor.sort
In your mongoose schema you can set timestamps. it will automatically set createdAt time stamp when you create a object from that schema and if you edit that particular object it set updatedAt timestamp.
As a example schema,
const mongoose = require('mongoose');
const markSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
mark: { type: Number },
student: { type: String },
},{
timestamps: true
});
module.exports = mongoose.model('Mark', markSchema);
like this you can set timestamps.

Why does Mongodb update work but mongoose doesn't?

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();

Mongoose findByIdAndUpdate removes not updated properties

I have the following Mongoose model:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
facebook: {
name: String,
email: String,
customerId: String
}
});
var User = mongoose.model('User', userSchema);
When I update a part of this document using findByIdAndUpdate
User.findByIdAndUpdate(id, {
$set: {
facebook: {
name: name
}
}
});
name gets updated, while email and customerId get removed (unset?).
I didn't find this documented.
Is there a way to update only specific document properties with findByIdAndUpdate?
FindByIdAndUpdate is actually Issues a mongodb findAndModify update command by a documents id.
The point is you are setting an object to overwrite the old object. if you want to update a field you need to modify your update object.
User.findByIdAndUpdate(id, {
$set: {
'facebook.name':name
}
});
This will only update the name field keeping rest of the field of the old object.

Automatically remove referencing objects on deletion in MongoDB

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);
}
};

Resources