I have a nested object which I am able to fetch properly but unable to store the the nested object values in the schema. Below are my code snippets:
header.js Router File
router.post('',(req, res)=>{
//console.log(req.body)
const header = new headerModel({
register:{
name: req.body.name,
url: req.body.url
},
logo:{
image: req.body.image,
altText: req.body.altText,
url: req.body.url
}
})
console.log(header)
})
module.exports = router
Header.js Schema File
const mongoose = require('mongoose')
const headerSchema = mongoose.Schema({
register: {
name: {
type: String
},
url: {
type: String
}
},
logo: {
image: {
type: String,
},
altText: {
type: String
},
url: {
type: String
},
}
})
module.exports = mongoose.model('header', headerSchema)
JSON
{
"register":{
"name":"Register",
"url":"/register"
},
"logo":{
"image":"/imagePath/ab.png",
"alttext":"Home",
"url":"/"
}
}
I need to store the value of name and url in register and signin objects respectively in Router File
the header in Router File when logged on console doesn't include register or logo
Because you get the data from JSON in the wrong way and you haven't saved the header yet. You can solve it by:
let header = new headerModel({
register:{
name: req.body.register.name,
url: req.body.register.url
},
logo:{
image: req.body.logo.image,
altText: req.body.logo.altText,
url: req.body.logo.url
}
})
header.save(function (err, doc) {
// Do some thing you want
})
Related information can be found here.
Related
So my knowledge of NodeJS and MongoDD are non-existent (just need to do a small code update for a friend) and I'm stuck.
Need to update a single document inside a collection via a unique id but can't seem to do it.
Here's the Model (I've trimmed it down and cut out all unnecessary data). I'm trying to update the field notes inside a transaction.
In short each entry in the given (an Agent) table will have a collection of multiple Transactions & Documents. I need to update a specific Transaction with the unique _id that is auto generated.
import { Schema, model } from 'mongoose';
interface Transaction {
first_name: string;
last_name: string;
type: string;
notes: string;
}
interface Agent {
org_id: number;
transactions: Array<Transaction>;
documents: Array<string>;
}
const transactionSchema = new Schema<Transaction>({
first_name: { type: String },
last_name: { type: String },
type: { type: String },
notes: String,
});
const transactionsSchema = new Schema<Agent>({
org_id: { type: Number },
transactions: [transactionSchema],
documents: [documentTypesSchema],
});
const AgentTransaction = model<Agent>(
'agent_transaction_table',
transactionsSchema
);
export default AgentTransaction;
Here's what I tried but didn't work (obviously), again I've trimmed out all unnecessary data. Just to clarify, the endpoint itself works, but the DB update does not.
import AgentTransaction from '../models/transaction'; // the above model
transaction.put('/notes', async (req, res) => {
const { org_id, transaction_id, notes } = req.body;
try {
const notesResult = await AgentTransaction.updateOne({
'transactions._id': transaction_id,
}, {
$set: {
'notes': notes
},
});
res
.status(200)
.json({ message: 'Updated', success: true, notesResult });
} catch (error) {
res.status(400).send(error);
}
});
So I figured it out. Maybe it'll help someone else as well.
const notesResult = await AgentTransaction.updateOne({
'transactions._id': { $in: [trunc2] },
}, {
$set: {
'transactions.$.notes': notes
},
});
The main issue was that the payload object needed to target the collection folder + the wildcard + the field, not just only the field.
Even though the question have been asked numerous time none of the answers have any idea to help me .
This is my mongoose Schema
const mongoose = require('mongoose')
const { Schema } = mongoose;
const recipeSchema = new Schema({
name: { type: String, required: true },
description: { type: String, required: true },
imagePath: { type: String, required: true },
ingredients:[
{
name:{type:String, required:true},
amount:{type:Number,required:true }
}
]
})
module.exports = mongoose.model("Recipe",recipeSchema);
what i need is to get the data from angular and store it to my database using node
const Recipe = require('../models/recipe.model');
const recipeCtrl={};
recipeCtrl.CreateRecipeServer =async(req, res, next)=>{
if(!req.file) {
return res.status(500).send({ message: 'Upload fail'});
}
else {
let ingredientArray=new Array()
ingredientArray.push(req.body.ingredients)
req.body.imageUrl = 'http://192.168.0.7:3000/images/' + req.file.filename;
const recipe=new Recipe({
name:req.body.name,
description:req.body.description,
imagePath:req.body.imageUrl,
ingredients:[
{
name:ingredientArray,
amount:ingredientArray }
]
});
await recipe.save();
}
Everything except the ingredients array works perfectly/as i require.
I am getting the ingredients as an array from formdata so it have to be JSON.stringfied inorder to append with the form. So what i am getting at backend is string . eg
**[{"name":"dasdasd","amount":2},{"name":"fsfsd","amount":2},{"name":"sdfsdgd","amount":3}]**
this is a string. Any ideas on how to convert it and store to database
use JSON.parse and choose first element of that
JSON.parse(data)[0]
I am trying to send an object created by MongoDB model as a body of post request in a jest test.
Here is the test:
test("post request successfully creates a new blog", async () => {
const newBlog = new Blog({
title: "My mundane day at home 3",
author: "AbG",
url: "https://www.google.co.in/",
likes: 11,
});
await api
.post("/api/blogs")
.send(newBlog)
.expect(201)
.expect("Content-Type", /application\/json/)
.catch((err) => console.log(err));
const blogs = await Blog.find({});
expect(blogs).toHaveLength(initialBlogs.length + 1);
});
As you can see, I am sending the newBlog as a body of request. But when I receive it in controller, the newBlog is present in the request.body._doc instead of request.body.
I think this has something to do with the mongoose model of blog.
const blogSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
url: {
type: String,
required: true,
},
likes: {
type: Number,
required: false,
default: 0,
},
});
module.exports = mongoose.model("Blog", blogSchema);
I cannot understand why this is happening.
I found out where I was going wrong.
In the test case, I was creating a mongodb schema instance and passing it as body of request instead of a plain JS object. And in the express app, I was trying to access the request body as a JS object. So that created a confusion.
The changes that I did:
In test:
Instead of
const newBlog = new Blog({....})
I did
const newBlog = {....}
So, I avoided passing mongodb object as request body and created the mongodb object using the constructor immediately before where I needed it.
Here is the post route:
blogsRouter.post("/", async (request, response) => {
const blog = new Blog(request.body);
const savedBlog = await blog.save();
response.status(201).json(savedBlog);
});
I currently have a model that includes the following:
title: {
type: Sequelize.STRING
}, name: {
type: Sequelize.STRING
}, images: {
type: Sequelize.STRING
}
I'm storing the file name of the images as a string on POSTGRES by using
//POST METHOD
app.post("/", (req, res) => {
MODEL.create({
images: JSON.stringify(req.files.map(file => file.filename))
})
})
when i try it without the JSON.stringify, i get an error saying images cannot be an array or object (problem 1)
My 2nd problem is now when I try to access the image in my get request I want to change the image from being a filename to a URL and thumbnail URL as below
url: ${baseUrl}${image}_full.jpg
thumbnailUrl: ${baseUrl}${image}_thumb.jpg
I have the following schema to store coordinates:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const LocationSchema = new Schema({
// Matches
loc: {
type:
{
type: String
},
coordinates: [Number]
},
member_id: {
type: String
}
});
LocationSchema.index({ loc: '2dsphere' });
mongoose.model('locations', LocationSchema);
I have also created a get route to get to the page where I want to show this stored coordinates data. When I hit the route I get the following in the console.log which I am using to debug:
{ loc: { coordinates: [ 74.360106, 31.497754 ], type: 'Point' },
_id: 5b5abd4bdcbd0f4e5c70b799,
member_id: 'HyQUa4_N7',
__v: 0 }
This looks fine to me since I am getting back the coordinates and the member ID. Following is the code for my get route using which I am passing the data to my express handlebars view:
// Manage Location
router.get('/userlocation/:member_id', ensureAuthenticated, (req, res) => {
Location.findOne({ member_id: req.params.member_id })
.then(locations => {
console.log(locations);
res.render('users/userlocation', { locations: locations });
})
.catch(error => {
console.log('could not find user location');
});
});
I am confused about how do I show this data in my HTML/View. Normally I use {{variable name}} to show data which is being passed into the view. what format should I use. I tried using {{locations.coordinates[0]}} but that gives me an error.
Please help. This is the first time I am attempting something like this in Node.
You can access the longitude like this:
{{locations.loc.coordinates[0]}}
I would suggest you should define schema like this:
location: {type: [Number], index: '2d'}, // [, ]