Mongoose updating a document by removing a single object from document - javascript

Can't find a solution for it :(
I'm doing a contacts app using Node, express and mongoose.
when a user goes to the route /contact/:id
this query gets executed:
Contact.findOne(req.dbQuery, function(err, data) {
res.json(data);
});
The Response is:
{
_id: 57 d71ceb57658ba24866a1b0,
__v: 0,
firstName: ['Doe', 'text'],
lastName: ['John', 'text'],
id: 4,
homePhone: ['', 'tel'],
cellPhone: ['', 'tel'],
birthday: ['', 'date'],
website: ['', 'url'],
address: ['test Adress', 'text'],
}
Each item in the array is getting displayed on the page as a label and a textbox
using ng-repeat.
Next to each textbox I have an X button to remove a textbox.
On each X button there's ng-click="remove(field)"
$scope.remove = function(field){ //field can be 'homePhone' or any item
delete $scope.record[field];
$scope.record.$update(function(updatedRecord){
$scope.record = updatedRecord;
})
};
Problem is, When I'm clicking on the X button and calling
remove('homePhone') (or any of the fields - 'cellPhone' or any other)
i'm sending the correct data to the server via req.body (I can see the data
without the removed field) but getting a response including the field I just
removed.
On the server I'm executing:
Contact.findOneAndUpdate({
_id: contact._id
}, req.body, {
upsert: true,
new: true
}, function(err, data) {
res.json(data);
});
I also have an "add new field" button that is adding a textbox by adding an item
to the array. I'm executing the same query on add new field
This is why I use {upsert: true, new: true}
Will I have to change everything?
Thanks a lot

please use $unset operator to remove any field from the document. that is the preferred way or removing fields from document when performing an update.

Related

Deleting an element from an Array, that is inside an Object

In my To-Do app, when a logged-in User completes a task, I would like to clear it from the MongoDB database.
Here is the code for my Schema.
const user = new mongoose.Schema({
username : String,
password : String,
task : [{
text : String,
day : String,
reminder : Boolean,
]}
})
For example, if Daryl completed text : "Gym" & day : "Feb 4th 5.30pm", I would like to only remove task[0] from Daryl's task Array.
Here is my attempt at doing so using Mongoose,
app.delete("/tasks", (req,res) => {
User.findOne( {_id : req.user.id}).then((target) => {
target.task.remove({text : req.body.text, day : req.body.day})
})
})
User.findOne({_id : req.user.id}) to only target the person that logged in
Once targeted, access task array using .task
and use .remove along with filters, to remove that entry from the array
I have console.logged() all the variables and it tallies with the data fields, however the entry is not being removed. What am I doing wrong?
I managed to solve my problem, hopefully this helps someone else
app.delete("/tasks", (req, res) => {
User.findByIdAndUpdate(req.user.id, {$pull: {"task": {text: req.body.text}}}, {safe: true, upsert: true},
function (err, node) {
// console.log here for debugging, if you want
})
})
This successfully erases items based on
req.user.id
"task" : {//whatever your stricter conditions are}
I still don't understand why my earlier attempts failed, but at least this one works.

Not able to read all the selected checkbox values from pug in express

The Express MDN tutorial here uses the following code to pull in checkbox values from pug.
From the main code, req.body.genre is supposed to return an array of selected values from a form as below
div.form-group
label Genre:
div
for genre in genres
div(style='display: inline; padding-right:10px;')
input.checkbox-input(type='checkbox', name='genre', id=genre._id, value=genre._id, checked=genre.checked )
label(for=genre._id) #{genre.name}
button.btn.btn-primary(type='submit') Submit
when req.body.genre is referenced in the section of code below in the final middleware function where the new Book model instance is created, it returns only the first value stored as string. Hence the genre field always ends up saving only one value even if multiple checkboxes were ticked in the form.
exports.book_create_post = [
// Convert the genre to an array.
(req, res, next) => {
if(!(req.body.genre instanceof Array)){
if(typeof req.body.genre==='undefined')
req.body.genre=[];
else
req.body.genre=new Array(req.body.genre);
}
next();
},
// Validate fields.
body('title', 'Title must not be empty.').isLength({ min: 1 }).trim(),
body('author', 'Author must not be empty.').isLength({ min: 1 }).trim(),
body('summary', 'Summary must not be empty.').isLength({ min: 1 }).trim(),
body('isbn', 'ISBN must not be empty').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
sanitizeBody('genre.*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
// Create a Book object with escaped and trimmed data.
var book = new Book(
{ title: req.body.title,
author: req.body.author,
summary: req.body.summary,
isbn: req.body.isbn,
genre: req.body.genre
});
The genre field has been defined to store an array of values
var BookSchema = new Schema(
{
title: {type: String, required: true},
author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
summary: {type: String, required: true},
isbn: {type: String, required: true},
genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
}
);
What should i do to be able to get req.body.genre as an array of selected values ?
I found the culprit
This one line of code for express validator created the issue
sanitizeBody('*').escape()
replaced it with
sanitizeBody('author').escape(),
sanitizeBody('title').escape(),
sanitizeBody('isbn').escape(),
sanitizeBody('summary').escape(),
sanitizeBody('genre.*').escape(),
Now everything works fine. the array is now passed through the req body.

Mongoose cast to ObjectID failed for value... but why

I know what the problem is, but can't figure out why it is happening. I have a simple recipe app using express and mongoose. User passes in recipe info via form and is saved to database via mongoose methods. This part seems to work perfectly and when I console.log using test data, I see that the following data is saved:
{
ingredients: [ 'peanut butter', 'jelly', 'bread' ],
_id: 5e47d564f775ce247052d01c,
name: 'pb jelly sammich',
author: 'rob',
oneLiner: 'classic pb jelly sammich',
image: 'picofpbsammich here',
method: 'add all the ingredients together and boom! pb jelly sammich.',
__v: 0
}
(This is also what shows when I check mongo db using db.recipes.find() and also what displays when I pass in the object to my ejs show template.
However, when I access my show route via get request, I get a long error message using the above test data. Here is they key part of the error message:
'Cast to ObjectId failed for value "picofpbsammich here" at path "_id" for model "Recipes"',
I understand what the problem is, but baffled as to why it is happening. Here is my show route:
app.get("/recipes/:id", function (req, res) {
console.log(req.params.id)
Recipe.findById(req.params.id, function (err, foundRecipe) {
if (err) {
console.log(err);
} else {
res.render("show", { recipe: foundRecipe });
}
})
})
console logging the req.params.id as shown above, prints the following:
5e47d564f775ce247052d01c
picofpbsammich here
The first line is the correct ID, the second is obviously not and the cause of the problem, but I have no idea where that could be coming from :S Why would req.params.id be pulling the VALUE of a property that is named something completely different?
I'm new to mongoose so it's probably something silly I'm doing and any explanations appreciated.
Here is the model:
var mongoose = require("mongoose");
let recipeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
author: String,
oneLiner: String,
ingredients: [String],
image: String,
method: String
})
module.exports = mongoose.model("Recipes", recipeSchema)
You posted the following code:
app.get("/recipes/:id", function (req, res) {
console.log(req.params.id)
Recipe.findById(req.params.id, function (err, foundRecipe) {
if (err) {
console.log(err);
} else {
res.render("show", { recipe: foundRecipe });
}
})
})
And you mention that in the console.log you receive:
5e47d564f775ce247052d01c
picofpbsammich here
Followed by the exception being logged:
'Cast to ObjectId failed for value "picofpbsammich here" at path "_id"
for model "Recipes"',
Makes me logically assume that you are making two requests, one of which the id is not valid, being:
picofpbsammich here
Mongoose is not able to cast this value to an ObjectId, hence you get the exception, which makes sense imo.

POSTING an array of objects to node.js/save to database using mongoose

I have a ReactJS form, in which you can dynamically add form "parts"(sections with form input). Here's an example of what I mean by "parts":
<div>
<input placeholder="Author" />
<input placeholder="Age" />
<input placeholder="Amount of books written" />
</div>
Something like this. You can add as many of these divs as you like.
I'm saving the values of these inputs in the state, which gives me a nested array like so:
this.state = {
formdata : [
{author: "somebody", age: 34, books: 0},
{author: "somebody else", age: 100, books: 1}
]
}
Right now I'm use axios post to post the data to node.js with express. This is my post function:
handleSubmit(e) {
axios.post('receivedata',
querystring.stringify({
formdata : this.state.formdata
}), {
headers : {"Content-Type": "application/x-www-form-urlencoded"}
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
And this is the mongoose schema that I use:
var EntrySchema = new mongoose.Schema({
formdata: [{type:String}],
updated_at: {type: Date, default: Date.now}
});
and this is how I (try to) send the data to my database:
router.post("/", function(req, res) {
newEntry.formdata = req.body.formdata;
newEntry.save(function (err) {
if(err)
res.send(err);
res.send("Entry added successfully!");
});
});
That doesn't work though and when I check the database, I receive an array with an empty string like so: formdata:[{""}]
I think the problem is with how the schema is set up, since, when I do console.log(this.state.formdata) it correctly returns the data. My next guess would be that axios is not able to send nested array, but after some research I found that that's not the case so I'm assuming that there's a special way to define nested arrays in the mongoose schema? How would I go about that?
Edit: I was thinking that maybe I could do something along the lines of:
var EntrySchema = new mongoose.Schema({
formdata: [{
author: String,
age: Number,
books: Number
}],
updated_at: {type: Date, default: Date.now}
});
I tried this and it doesn't work either. Now, I don't know if I'm on the right track or how else to do this.
I also tried changing the Content-Type in the header to "application/ json", as suggested in another answer. Once again, it didn't work.
Any help is appreciated.
Okay so after some playing around I figured it out: I used querystring.stringify() before, after changing it to JSON.stringify() it worked perfectly for me.

Preventing duplicate records in Mongoose

I'm fairly new to MongoDb / Mongoose, more used to SQL Server or Oracle.
I have a fairly simple Schema for an event.
EventSchema.add({
pkey: { type: String, unique: true },
device: { type: String, required: true },
name: { type: String, required: true },
owner: { type: String, required: true },
description: { type: String, required: true },
});
I was looking at Mongoose Indexes which shows two ways of doing it, I used the field definition.
I also have a very simple API that accepts a POST and calls create on this collection to insert the record.
I wrote a test that checks that the insert of a record with the same pkey should not happen and that the unique:true is functioning. I already have a set of events that I read into an array so I just POST the first of these events again and see what happens, I expected that mongo DB would throw the E11000 duplicate key error, but this did not happen.
var url = 'api/events';
var evt = JSON.parse(JSON.stringify(events[0]));
// POST'ed new record won't have an _id yet
delete evt._id;
api.post(url)
.send(evt)
.end(err, res) {
err.should.exist;
err.code.should.equal(11000);
});
The test fails, there is no error and a duplicate record is inserted.
When I take a look at the collection I can see two records, both with the same pkey (the original record and the copy that I posted for the test). I do notice that the second record has the same creation date as the first but a later modified date.
(does mongo expect me to use the latest modified version record???, the URL is different and so is the ID)
[ { _id: 2,
pkey: '6fea271282eb01467020ce70b5775319',
name: 'Event name 01',
owner: 'Test Owner',
device: 'Device X',
description: 'I have no idea what\'s happening',
__v: 0,
url: '/api/events/2',
modified: '2016-03-23T07:31:18.529Z',
created: '2016-03-23T07:31:18.470Z' },
{ _id: 1,
pkey: '6fea271282eb01467020ce70b5775319',
name: 'Event name 01',
owner: 'Test Owner',
device: 'Device X',
description: 'I have no idea what\'s happening',
__v: 0,
url: '/api/events/1',
modified: '2016-03-23T07:31:18.470Z',
created: '2016-03-23T07:31:18.470Z' }
]
I had assumed that unique: true on the field definition told mongo db that this what you wanted and mongo enforced that for you at save, or maybe I just misunderstood something...
In SQL terms you create a key that can be used in URL lookup but you can build a unique compound index, to prevent duplicate inserts. I need to be able to define what fields in an event make the record unique because on a form data POST the submitter of a form does not have the next available _id value, but use the _id (done by "mongoose-auto-increment") so that the URL's use from other parts of the app are clean, like
/events/1
and not a complete mess of compound values, like
/events/Event%20name%2001%5fDevice%20X%5fTest%20Owner
I'm just about to start coding up the so for now I just wrote a simple test against this single string, but the real schema has a few more fields and will use a combination of them for uniqueness, I really want to get the initial test working before I start adding more tests, more fields and more code.
Is there something that I should be doing to ensure that the second record does not actually get inserted ?
It seems that you have done unique indexing(at schema level) after inserting some records in db.
please follow below steps to avoiding duplicates -
1) drop your db:
$ mongo
> use <db-name>;
> db.dropDatabase();
2) Now do indexing at schema level or db level
var EventSchema = new mongoose.Schema({
pkey: { type: String, unique: true },
device: { type: String, required: true },
name: { type: String, required: true },
owner: { type: String, required: true },
description: { type: String, required: true },
});
It will avoid duplicate record insertion with same pKey value.
and for ensuring the index, use command db.db_name.getIndexes().
I hope it helps.
thank you
OK it looks like it has something to do with the index not having time to update before the second insert is posted (as there is only 9ms between them in my test suite).
need to do something about inserts waiting for "index"
needs to be API side as not all users of the API are web applications
I also found some other SO articles about constraints:
mongoose unique: true not work
Unique index not working with Mongoose / MongoDB
MongoDB/Mongoose unique constraint on Date field
on mongoose.connect add {useCreateIndex: true}
It should look like this
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
add:
EventSchema.index({ pkey: 1 }, { unique: true });
// Rebuild all indexes
await User.syncIndexes();
worked for me.
from https://masteringjs.io/tutorials/mongoose/unique

Categories

Resources