Insert into an existing Record?

Insert into an existing Record?
0

#1

Good evening. I’m working on the Exercise Tracker and trying to figure out how to insert a new exercise log into an existing record.

This is what I have so far:

var findAndUpdate = function(userInput, done) {
	User.findOneAndUpdate(
		{
			_id: userInput.user_id
		}, {
			log: [{
				description: userInput.desc,
				duration: userInput.dur,
				date: userInput.date
             }]
		}, (err, data) => {
			if (err) {
				done(err);
			}
			done(null, data);
		}
	)
};

The problem with that code is it updates the exercise log, instead of adding a new one. So I tried this instead:

User.insert(
	{
	_id: userInput.user_id,
	log: [{
		description: userInput.desc,
		duration: userInput.dur,
		date: userInput.date
    }]
}, (err, data) => {
	if (err) {
		done(err);
	}
	done(null, data);
})

The problem with that code is I’m getting an error:

TypeError: User.insert is not a function

I have the User schema set up properly, so there must be something wrong with the way I wrote the insert code?

Live Version: https://dog-comic.glitch.me/


#2

findOneAndUpdate totally replaces the field you are requesting with your new argument, for instance in your case it replaces the entire log field of your document with the new one you assigned it. So, if you want to preserve what was in your previous log, then you must find it first, append your new entry and update the document with the newly appended entry. Example:

User.findById(id,(err, oldDoc)=>{
     \\ now you have the document you need to update
     const updatedLog = [...oldDoc.log, newLog]
     User.findOneAndUpdate(id, {log: updatedLog}, (err, dbUpdated)=>{
           \\ Now your db should be updated with the new entry
     })
})

You’d do something like the above, note that findOneAndUpdate will not return the new document unless you set the option {new: true} see the docs below
https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate


#3

That helped me a lot, thank you! I was able to get things sorted once I used the oldDoc data with the newDoc data.