I have a form with the input fields "firstName", "lastName" and "assetTag". I want to submit that form and post all that data plus one additional field called "modelType". The data from the modelType field is from the function call si.system() but i'm not sure how to pass that into the Model because it's a promise.
How can I pass the data from my console.log(data.model) into my formData?
app.js post request:
app.post('/', (req, res) => {
si.system()
.then(data => console.log(data.model))
.catch(error => console.error(error))
const formData = {
firstName: req.body.firstName,
lastName: req.body.lastName,
assetTag: parseInt(req.body.assetTag)
}
const system = new System(formData);
system.save()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
});
Model:
const mongoose = require('mongoose');
var SystemSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
assetTag: {
type: Number,
required: true
},
modelType: {
type: String,
required: true
}
});
module.exports = mongoose.model('System', SystemSchema);
if you are talking about getting that value out of the promise you need to look into async / await.
here's the code
app.post('/', async (req, res) => {
let data = await si.system();
const formData = {
firstName: req.body.firstName,
lastName: req.body.lastName,
modelType: data.model,
assetTag: parseInt(req.body.assetTag)
}
const system = new System(formData);
system.save()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
});
Related
I am trying to create a followers/following function in my project. However I cannot seem to update the DB correctly. I'm able to send the ids as they both print when I console.log but nothing in my DB updates and I do not get any response in my frontend.
route
app.put('/api/follow', async function (req, res, next){
const { id } = req.query;
const userFrom = req.body.data
console.log('OTHER USER ID',id)
console.log('CURRENT ID', userFrom)
User.findByIdAndUpdate(id), {
$push:{followers:req.body.data}
},{new:true},
(err,result)=>{
if(err) {
if(err) return res.status(400).send(err)
}
User.findByIdAndUpdate(req.body.data), {
$push:{following:id}
},{new:true}.then(result=> {
res.json(result)
}).catch(err=>{
return res.status(422).json({error:err})
})
}
})
user model
const mongoose = require("mongoose");
const User = mongoose.model(
"User",
new mongoose.Schema({
username: String,
email: String,
password: String,
phoneNo: String,
bio: String,
filePath: String,
following: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
followers: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
})
);
module.exports = User;
my route end function
const clickHandler = () => {
const currentID = currentUser.id;
const id = this.props.id;
console.log('CURRENT ID',currentID)
console.log('otherUserID',id)
Axios.put(`http://localhost:8080/api/follow/?id=${id}`, { data: currentID }, { headers: authHeader() })
.then(response => {
if (response.data.success) {
console.log('FOLLOWED', response.data)
// this.setState({ userDetails: response.data.details })
} else {
alert('Error')
}
})
}
This should be
User.findByIdAndUpdate(id, {
You should not close the bracket after id but after new: true})
I'm working on a twitter clone to learn MERN stack, here's a new tweet route
router.route('/new')
.post( (req, res) => {
const { errors, isValid } = validateTweet(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
let tweet = new Tweet({
content: req.body.content,
created_by: req.user.id
})
User.findById(req.user.id, (err, user) => {
if (err) return res.status(400).json(err)
user.tweets.push(tweet._id);
user.save();
});
tweet.save();
return res.status(201).json(tweet);
});
Which does not return timestamps for the tweet, how can i achieve this without querying the database for the tweet before returning it?
Here's the model just in case:
const tweetSchema = new Schema({
content: {
type: String,
required: true,
minlength: 1,
maxlength: 128,
trim: true
},
created_by: {
type: Schema.Types.ObjectId, ref: 'User',
required: true
}
}, {
timestamps: true
});
const Tweet = mongoose.model('Tweet', tweetSchema);
What i ended up doing was making the funcion async then returning the result of the fulfilled save(). Not sure if this is a good practice or not.
router.route('/new')
.post( async (req, res) => {
const { errors, isValid } = validateTweet(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
let tweet = new Tweet({
content: req.body.content,
created_by: req.user.id
})
User.findById(req.user.id, (err, user) => {
if (err) return res.status(400).json(err)
user.tweets.push(tweet._id);
user.save();
});
tweet = await tweet.save();
return res.status(201).json(tweet);
});
I am new to node, express wanted a help regarding validation.I am able to validate the data corresponded to post method but for put method the data is not able to get validated.What should be done for the data to get validated in put method?
Below is the user Model
const userSchema = new Schema({
name: {
type: String,
minlength: 3,
required: true,
validate:{
validator:function(value){
return value.length >=3
},
msg:function(){
return 'name is less than 3 characters'
}
}
},
const User = mongoose.model('User', userSchema)
module.exports = User
Below is the controller for user
const express = require('express')
const router = express.Router()
const Customers = require('../model/customers')
router.get('/', (req, res) => {
Customers.find()
.then((customer) => {
res.json(customer)
console.log(customer)
})
.catch(err => res.send(err))
})
router.post('/', async (req, res) => {
let customerData = new Customers({
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile
})
await customerData.save()
.then((customer) => {
res.json(customer)
console.log('customer is....', customer)
})
.catch(err => res.send(err))
})
router.put('/:id', async (req, res) => {
let apiId = req.params.id
const customerData = await Customers.findByIdAndUpdate(apiId,
{
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile
})
if (customerData) {
res.json(Object.assign(customerData, req.body))
}
else {
res.status(404).send('Url did not respond')
}
})
router.delete('/:id', async (req, res) => {
let apiId = req.params.id
const customerData = await Customers.findByIdAndRemove(apiId)
if (customerData) {
res.send(customerData)
}
else {
res.status(404).send('Url did not respond')
}
})
module.exports = { customerController: router }
As per mongoose docs
Mongoose also supports validation for update(), updateOne(),
updateMany(), and findOneAndUpdate() operations. Update validators are
off by default - you need to specify the runValidators option
So you have to set runValidators: true
Customers.findByIdAndUpdate(apiId,
{
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile
}, { runValidators: true } )
I'm learning to use Node.js and MongoDB. I have a problem when I try to save data to the database.
Here's my code
const Test = require('../models/test');
const test = (req, res, next) => {
let url = "http://localhost:3000/article"
request(url, (req, (err, fields) => {
if (err) {
return res.status(400).json({
error: "error"
})
}
var objTest = JSON.parse(fields.body);
console.log(objTest.user)
let test = new Test(objTest)
console.log("ini",test)
test
.save()
.then(result => {
res.send(result)
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}))
}
here my Test Schema
const testSchema = new mongoose.Schema(
{
tittle: {
type: String,
index: true,
},
content: {
type: String,
},
postedBy: { type: mongoose.Schema.ObjectId, ref: 'Author' },
created: {
type: Date,
default: Date.now,
},
},
{
timestamps: true,
},
);
module.exports = mongoose.model('Test', testSchema, 'tests');
The response in Postman is only id, createdAt and updatedAt. Thank you.
I'm connecting a Angular 2 app to MongoDB via Mongoose.
I'm trying to store some data, but i obtain an error on all required properties.
I set up a schema, serverside:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var uniqueValidator = require("mongoose-unique-validator");
var schema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
nome: {
type: String,
required: true
},
cognome: {
type: String,
required: true
},
dataNascita: {
type: Date
},
telefono: {
type: String
},
classifica: {
type: String
}
});
schema.plugin(uniqueValidator);
module.exports = mongoose.model("User", schema);
The user object is clearly filled:
Mongoose responds with an error:
Thanks in advance for any help.
Max
Update:
The call from a Angular service:
#Injectable()
export class AuthService {
constructor(private http: Http) {
}
addUser(utente: Utente) {
const body = JSON.stringify(utente);
return this.http.post('http://localhost:3000/utente', body)
.map((response: any) => {
console.log(response);
response.json();
})
.catch((error: Response) => Observable.throw(error.json()
));
}
}
The Moongose call:
var express = require('express');
var router = express.Router();
var User = require('../models/users');
router.post('/', function (req, res, next) {
var user = new User({
email: req.body.email,
password: req.body.password,
nome: req.body.nome,
cognome: req.body.cognome,
dataNascita: req.body.dataNascita,
telefono: req.body.telefono,
classifica: req.body.classifica
});
console.log(res);
user.save(function (err, result){
console.log(err);
console.log(res);
if (err){
return res.status(500).json({
titolo: "Errore durante il salvataggio",
errore: err
});
}
res.status(201).json({
messaggio: 'Utente salvato correttamente',
oggetto: res
});
});
});