I'm trying to update an item in a mongoDB, but I can't get it to work properly. I've googled the question and I can't seem to find what I'm doing wrong. I don't get any errors in the console, it actually says the update was successful. So far I've been able to create and find items in the DB just fine..Here's my code if anyone can help me spot the problem I'd really appreciate it!
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/fruits", { useNewUrlParser: true, useUnifiedTopology: true });
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number
});
const Fruit = mongoose.model("Fruit", fruitSchema);
// CREATE
// Fruit.create({
// name: "Grape",
// rating: "7"
// }, (err, fruit) => {
// if (err) {
// console.log(err);
// } else {
// console.log("SAVED FRUIT!");
// console.log(fruit);
// }
// });
// READ
// Fruit.findById({ _id: "5f85e2e36ef7e00c97ac484f" }, (err, fruit) => {
// if (err) {
// console.log(err);
// } else {
// console.log("FOUND FRUIT!");
// console.log(fruit);
// }
// });
// UPDATE
Fruit.findByIdAndUpdate({ _id: "5f85e2e36ef7e00c97ac484f" }, { $set: { color: "Green" } }, (err, fruit) => {
if (err) {
console.log(err);
} else {
console.log("UPDATED FRUIT!");
console.log(fruit);
}
});
Here's what the DB looks like,
{
"_id" : ObjectId("5f85e2e36ef7e00c97ac484f"),
"name" : "Kiwi",
"rating" : 6,
"__v" : 0
}
{
"_id" : ObjectId("5f85e3003dbb9d0c9bcca90d"),
"name" : "Grape",
"rating" : 7,
"__v" : 0
}
Define color in mongoose schema
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
color: String // add this one.
});
Also while updating, no need to use $set, just pass the object.
Fruit.findByIdAndUpdate({ _id: "5f85e2e36ef7e00c97ac484f" }, { color: "Green" }, (err, fruit) => {
if (err) {
console.log(err);
} else {
console.log("UPDATED FRUIT!");
console.log(fruit);
}
});
Related
I don't know why it's not being inserted. it doesn't show an error or anything so i couldn't figure out the problem.
the tags [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ].
here is my insert function:
insert: async(req,res)=> {
const {userid,tags}=req.body;
console.log("userid", userid)
console.log("tags", tags) //tag [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ]
try {
User.findByIdAndUpdate(
userid,
{ $push: { tags: {$each : tags } }} ,
);
return res.status(200).send({msg:"success"});
} catch (error) {
console.log(error);
res.status(500).send({ msg: "Something went wrong" });
}
}
my user schema:
tags: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag'
}]
tag schema:
const TagSchema = new Schema({
name: {
type: String
},
type: {
type: Object,
},
timestamp: {
type: Date,
default: Date.now
},
});
Most codes i saw do it like that but i couldn't figure out why mine isn't working
Since you are using async, you can make use of await to see it if is saved or not. Rewriting logic in this way you can catch saved instance and return success or failure.
insert: async(req,res)=> {
const {userid,tags}=req.body;
console.log("userid", userid)
console.log("tags", tags) //tag [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ]
const doc = await User.findByIdAndUpdate(
userid,
{ $push: { tags: {$each : tags } }} ,{new:true}
);
if (!doc) return res.status(500).send({ msg: "Something went wrong" });
return res.status(200).send({msg:"success"});
}
Checking the router on the server side it console logs the right values, only the follow error is popping up in here. Trying to build a counter that should update the value on the backend. But the problem I have is that value will not be stored in there. When using Postman the value will be stored successfully. What is the solution that can fix this issue.
export const incrementProduct = (index, updateAmount, id) => {
return dispatch => {
dispatch(increment(index));
try {
axios.patch(`${API_URL}/:${id}`, {
amount: updateAmount
}).then(res => {
console.log(res.config);
})
} catch(err) {
console.log(err)
}
}
}
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
amount: {
type: Number,
required: true
},
editable: {
type: Boolean,
required: true
},
data: {
type: Date,
default: Date.now
}
});
// update
router.patch('/:postId', async(req, res) => {
console.log('update', req.params.postId + 'amount ' + req.body.amount)
try {
const updatedPost = await Post.findByIdAndUpdate(
{_id: req.params.postId}, <--- this cause the console error...
{$set:
{
amount: req.body.amount
},
})
console.log('try')
res.json(updatedPost)
} catch(err) {
console.log(err + 'test ')
res.json({ message: err })
}
})
You need to remove : in the patch url like this:
axios.patch(`${API_URL}/${id}`
Also findByIdAndUpdate requires only the value of _id, so you can only pass the value like this:
await Post.findByIdAndUpdate(req.params.postId, ...
findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).
I am trying to update the object inside the document
Document: Cats
{
"_id": "5e5cb512e90bd40017385305",
"type": "cat"
"history": [
{
"id": "randomID",
"content": "xyz",
},
{
"id": "randomID2",
"content": "abc",
}
]
}
Code to select and update the object inside the history array:
const editHistory = async (_, { input }, ctx) => {
let query = { _id: input.catId, "history.id": input.historyId };
let update = { $set: { "history.$": input.history } };
let options = {
new: true,
fields: { history: { $elemMatch: { id: "randomID" } } }
};
let cat = await ctx.models.cats.findOneAndUpdate(query, update, options);
return cat;
};
Input has following values
input: {
catId: "5e5cb512e90bd40017385305",
historyId: "randomID",
history: {
id: "randomID",
content: "new content"
}}
I tried using Projection, I used select changed it to field, found in mongoose documentation.
I still couldn't update the values. Is there anything wrong with the way i am querying or selecting the subfield.
Found the Solution for it by going through more detail of the operator($set) and option(new, fields).
Question:
const editHistory = async (_, { input }, ctx) => {
let query = { _id: input.catId, "history.id": input.historyId };
let update = { $set: { "history.$": input.history } };
let options = {
// using new option would return the new document
new: true,
/* using fields option would select the based on the given key, but using new:
true with fields will throw error: 'cannot use a positional projection and
return the new document'
*/
fields: { history: { $elemMatch: { id: "randomID" } } }
};
let cat = await ctx.models.cats.findOneAndUpdate(query, update, options);
return cat;
};
This post below answers that question for *error: 'cannot use a positional projection and return the new document'.
https://stackoverflow.com/a/46064082/5492398
Final Solution:
const editHistory = async (_, { input }, ctx) => {
let query = { _id: input.catId, "history.id": input.historyId };
let update = { $set: { "history.$": input.history } };
let options = {
new: true
};
let cat = await ctx.models.cats.findOneAndUpdate(query, update, options);
return cat;
};
Removing field option, since I don't need the unmodified selection before atomic modification, solves the question.
I'm extremely perplexed by this issue that I'm having with mongo/mongoose. I'm essentially trying to get an array of products, delete a certain product from the array, and then update the shopping chart with the new array that omits the selected product. Here's the snippet of code I'm dealing with:
const remove = (req, res, next) => {
console.log('here is the product id ' + req.body.cart.product)
delete req.body._owner // disallow owner reassignment.
Cart.find({_id: req.user.cartId})
.then((products1) => {
console.log("array of products: " + products1[0].product)
const index = products1[0].product.indexOf(req.body.cart.product)
console.log("index valeu: " + index)
if (index > -1) {
products1[0].product.splice(index, 1)
return products1[0].product
}
return products1[0].product
})
.then((products2) => {
console.log('Second Promise Input: ' + products2)
Cart.update({_id: req.user.cartId}, {$set: {product: products2}})
})
.then(() => res.sendStatus(204))
.catch(next)
}
And here's the output from my server:
Server listening on port 4741
here is the product id 5952b57ea52d092b8d34c6b0
array of products: 5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0
index valeu: 0
Second Promise Input: 5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0,5952b57ea52d092b8d34c6b0
PATCH /carts-decrease/595b037e128cfd37e0c864d7 204 38.773 ms
According to my console.logs, I'm getting the array just the way I want it but it simply does not update the shopping cart with the new array. I've been staring at this code for far too long and I'd appreciate a second set of eyes on this. Thanks.
P.S. Ignore the fact that the product ids are all the same, its just a testing variable
Cart Schema:
'use strict'
const mongoose = require('mongoose')
const cartSchema = new mongoose.Schema({
product: {
type: Array,
required: false
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: false
}
}, {
timestamps: true,
toJSON: {
virtuals: true,
transform: function (doc, ret, options) {
const userId = (options.user && options.user._id) || false
ret.editable = userId && userId.equals(doc._owner)
return ret
}
}
})
const Cart = mongoose.model('Cart', cartSchema)
module.exports = Cart
Product Schema:
'use strict'
const mongoose = require('mongoose')
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
}
}, {
toJSON: {
virtuals: true
}
})
const Product = mongoose.model('Product', productSchema)
module.exports = Product
Show request:
const show = (req, res) => {
const product = {}
product.array = []
// console.log(req.cart.product)
const promises = []
Promise.all(req.cart.product.map(function (id) {
return Product.find({_id: ObjectId(id)})
})).then(function (products) {
console.log(products)
req.cart.product = products
return res.json({
cart: req.cart.toJSON({virtuals: true, user: req.user})
})
}).catch(function (err) {
console.log(err)
return res.sendStatus(500)
})
}
I would recommend you to slightly modify your cartSchema and store products in the form of an array of embedded documents:
const cartSchema = new mongoose.Schema({
products: [{
name: { type: String },
price: { type: Number }
...
}]
...
});
If you do this you can simply use the $pull update operator to remove products from your cart:
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
In your case the query should then look like this:
Cart.update(
{ _id: req.user.cartId },
{ $pull: { products: { '_id': req.body.cart.product } }}
);
As the embedded documents will have their own ObjectId there will only be one document matching the query.
I'm not sure why the removal doesn't work using the latter method. (foundList is not null)
Latter method:
List.findOne({name: listType}, function(err, foundList){
if (err){
console.log(err);
} else {
foundList.updateOne({}, { $pull: { item: { _id: itemID } } });
console.log('deletion success');
res.redirect("/" + listType);
}
});
}
Schema:
const itemSchema = {text: String}
const listSchema = {
name: String,
item: [itemSchema]
}
Below line is wrong and wont work. This is because foundList contains result of the query findOne.
foundList.updateOne({}, { $pull: { item: { _id: itemID } } });
After you call List.findOne({name: listType}, function(err, foundList), foundList contains result of the query, and you cannot call any query/mongoose-api on that. You need to call mongoose APIs like updateOne on the model object, only then you will get the result.
What you can do is you can modify that document and then save it. You can do that like this:
List.findOne({name: listType}, function(err, foundList){
if (err){
console.log(err);
} else {
let index = foundList.findIndex((list: any) => list.item._id == itemID );
if (index !== -1) {
foundList.splice(index, 1);
}
foundList.save().then(()=>{
console.log('deletion success');
res.redirect("/" + listType);
})
}
})
Or you can do all that in one query. Try this:
List.findOneAndUpdate({name: listType}, {
$pull: {
item: { _id: itemID }
}, {new:true})
.then((response) => {
console.log('deletion success');
res.redirect("/" + listType);
})
.catch((err) => res.json(err));
NOTE: Also make sure itemID is of type ObjectId and not string. You can typecast string to ObjectId as shown here.