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"});
}
Related
i have a object which looks like this:
{
"title": "675756",
"release_date": "2022-01-16",
"series": "Better Call Saul",
"img": "https://upload.wikimedia.org/wikipedia/en/0/03/Walter_White_S5B.png",
"characters": [],
"id": 1
}
to an characters array i want to add the id of characters.
I do it by form and then i handle submit like this:
const handleSubmit = (values) => {
console.log("dodano aktora do filmu!");
console.log(values);
addActorToMovie(values);
history.goBack();
};
the addActorToMovie action:
export const addActorToMovie = (resp) => ({
type: types.ADD_CHAR_TO_MOVIE,
payload: resp,
});
and the reducer:
case types.ADD_CHAR_TO_MOVIE:
console.log(action.payload);
return {
...state,
...state.episodes.map(function (item) {
return item.id === action.payload.episodeId
? {
id: item.id,
title: item.title,
release_date: item.release_date,
series: item.series,
img: item.img,
characters: [...item.characters, action.payload.actor],
}
: { ...item };
}),
};
It all works, but the problem is that i dont want to do it loccaly. Im using an database with json-server, and I want to do an Axios Request so that it would add a data to the database.
And i don't know how to do this, when i use axios.post it adds an object to my episodes array, if im using axios.put it changes an object. Is there any possibility to push the data to an array as i do it with the code above, but with axios so that it would be added to database?
My approach looked like this:
export const addActorToMovieAxios = (value) => {
console.log(value);
return async (dispatch) => {
try {
const response = await axios.post(
`http://localhost:3000/episodes/`,
value
);
console.log(response);
dispatch(addActorToMovie(response.data));
} catch (ex) {
console.log(ex);
}
};
};
but as I said this does add a new object to an array.....
"episodes": [
{
"title": "675756",
"release_date": "2022-01-16",
"series": "Better Call Saul",
"img": "https://upload.wikimedia.org/wikipedia/en/0/03/Walter_White_S5B.png",
"characters": [],
"id": 1
},
{
"episodeId": 1,
"actor": "1",
"id": 2
}
]
So just to be clear I understand your question, you have an object that already exists in your DB, and you want to push something onto the 'characters' array in that existing object, without creating a new object, correct?
To do this, I would use Mongo for your DB and define two Mongoose Schemas, one for the existing object (let's call it TVShow) and one for the Characters within that object. Your two Schemas will look like this:
TVShowModel.js:
const mongoose = require('mongoose');
const CharacterModel = require('./CharacterModel')
const TVShowScheme = new mongoose.Schema({
title: {
type: String,
},
release_date: {
type: Date,
},
series: {
type: String,
},
img: {
type: String,
},
characters:[
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Student'
},
],
examQuestions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'CharacterModel'
}
]
})
module.exports = mongoose.model('TVShowModel', TVShowScheme )
CharacterModel.js:
const mongoose = require('mongoose');
const CharacterModel= new mongoose.Schema({
characterName: {
type: String,
},
actorName: {
type: String,
},
}) // add any other fields you want here
module.exports = mongoose.model('CharacterModel', CharactModelScheme )
Then, create your Axios post request. Make sure you send when you send the 'value' variable to your server, it contains the id (or perhaps the unique title) of the object you'll be 'pushing' to. Push won't work in axios/react, so we'll use the 'spread' opperator instead.
Your router will look like this:
const CharacterModel= require ('../models/CharacterModel');
const TVShowModel= require ('../models/TVShowModel');
const router = express.Router();
router.post('/episodes', async function(req,res){
try{
const tvshow = await TVShowModel.find({title: req.body.title})
// edit as needed
console.log("FOUND TV Show: "+tvshow )
const characterName= req.body.characterName
const actorName = req.body.actorName
const newCharacter = new CharacterModel({
characterName,
actorName,
})
console.log("new character created: "+newCharacter)
tvshow[0].CharacterModel = [...tvshow[0].CharacterModel,newCharacter];
await tvshow[0].save()
.then(()=>res.json('New Character Added to DB'))
.catch(err=>res.status(400).json('Error: ' + err))
} catch(e){
console.log(e)
}
})
Hope this was clear!
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);
}
});
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'm trying to exclude a junction model from a query with the association of a model, this is how they are associated:
Warehouse.associate = function(models) {
Warehouse.Products = Warehouse.belongsToMany(models.Product, {
as: {
singular: 'product',
plural: 'products',
},
through: models.WarehouseProducts,
foreignKey: "warehouse_id",
otherKey: "product_id",
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
});
}
Product.associate = function(models) {
Product.Warehouses = Product.belongsToMany(models.Warehouse, {
as: {
singular: "warehouse",
plural: "warehouses"
},
through: models.WarehouseProducts,
foreignKey: "product_id",
otherKey: "warehouse_id",
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
});
}
And this is the code that I use to retrieve the product of a warehouse:
export const prefetchWarehouse = [
validator.params.warehouse,
async function(req, res, next) {
try {
if (validator.errors(req)) {
throw validator.stack;
} else {
req.warehouse = await Warehouse.findById(req.params.warehouse);
next();
}
} catch (err) {
next(err);
}
}
];
export const getProduct = [
validator.params.product,
async function(req, res, next) {
const result = await req.warehouse.getProducts({
where: {
id: {
[Op.eq]: req.params.product
}
},
plain: true
});
console.log('===>', result);
}
]
And this is the output:
Is there anyway to avoid not getting back that association?
I've ran across this behavior, and i solved it by just setting joinTableAttributes to an empty array like so joinTableAttributes: [].
export const getProduct = [
validator.params.product,
async function(req, res, next) {
const result = await req.warehouse.getProducts({
joinTableAttributes: [], // Here
where: {
id: {
[Op.eq]: req.params.product
}
},
plain: true
});
console.log('===>', result);
}
]
hope that helps you.
One way to solve this is using the junction model in my handler to avoid it:
export function WarehouseProducts(WarehouseProducts) {
WarehouseProducts.associate = function(models) {
WarehouseProducts.Products = WarehouseProducts.belongsTo(models.Product, {
as: "product"
});
};
}
And then in the handler:
const result = await WarehouseProducts.findOne({
where: {
warehouse_id: { [Op.eq]: req.params.warehouse },
product_id: { [Op.eq]: req.params.product }
},
include: [ "product" ]
});
res.json(result.product);
Although, it would be nice to doing in the way that I was looking for because the same function "prefetchWarehouse" is reused in others endpoints, so that would help to avoid. Even though the code looks more optimized, but anyway, if someone else has any suggestion I would appreciate it.
Thanks.
On client.save() below, I have the following error (which is catch properly):
DocumentNotFoundError: No document found for query "{ _id: '5bfbce595be7d1047c976e6b' }"
app.put('/api/client', function (req, res) {
Client.findOne(new mongoose.Types.ObjectId(req.body._id)).then(client => {
//This is OK, I can see client and its properties
client.name = req.body.name;
//This is OK, I can see the updated client and its properties
client.save().then(test => {
console.log("ERR=" + err);
console.log(test);
}).catch(err => console.log("ERR :" + err));
res.json(client);
});
});
The model is as such:
mongoose.model('Client', {
_id: {type: String, default: ''},
name: {type: String, default: ''},
creationDate: {type: Date, default: ''}
});
How come the document is found on FindOne() and no more on save()?
try to do so:
mongoose.model('Client', {
_id: { type: mongoose.Schema.Types.ObjectId, auto: true },
name: { type: String, default: '' },
creationDate: { type: Date, default: Date.now() }
});
And
Client.findOne().where({_id : req.body._id})...