I am trying to access a document and get the results to console. Mongoose debug shows that there is a document, yet returns an empty record.
//mongoose connect to db
var db = mongoose.createConnection('mongodb://localhost/mean-dev1/', function(err) {
if (err) throw err;
});
db.once('open', function callback() {
var tripSchema = mongoose.Schema(
{ title: String,
fromDate: Date,
tillDate: Date,
price: Number,
details: String,
availability: Number
});
// Model definition
var TripObj = db.model('TripObj', tripSchema, 'tripmodel');
TripObj.find(function(err, data) {
if (!err){
console.log('%s', data); //gets undefined
console.log("written...", data);
}else{
throw err;
process.exit();
}
});
}
and here is the console output
...
Migrations: Up to date at version 003
Mongoose: tripmodel.find({}) { fields: { title: 1 } }
is undefined?
written... []
Figured it out, the problem was with my initial connection. So changed the code a bit.
//connects to mongoose datasource and populates the data.json file in app
mongoose.disconnect();
mongoose.connect('mongodb://localhost/tripDB/', function(err) {
if (err) throw err;
}),
Schema = mongoose.Schema
var db = mongoose.connection;
db.once('open', function callback() {
var tripSchema = mongoose.Schema(
{
availability: Number,
details: String,
fromDate: Date,
price: Number,
tillDate: Date,
title: {type:String, ref:'TripObj'}
});
// Model definition
var TripObj = mongoose.model('TripObj', tripSchema, 'trips');
TripObj.find(function(err, data) {
if (!err){
var newdata = data;
//console.log('%s is undefined?', newdata);
fs.writeFileSync(path.join(__dirname, '../../../../' + 'content/themes/traveller/assets/js' + '/data.json'), JSON.stringify(newdata));
console.log("written succesfully", data);
process.exit();
}else{
throw err;
}
});
});
Related
I am trying to take user input and then add a drug(medicine) to MongoDB. But it is not working and I am getting the error "Add proper parameter first". The user input should be patient name, drug name, dosage, frequency, adherence, and reason for not taking medicine. Please help!
app.post("/add-drug", (req, res) => {
try {
if (req.body && req.body.patient_name && req.body.drug_name && req.body.dosage && req.body.frequency && req.body.adherence && req.body.reason) {
let new_drug = new drug();
new_drug.patient_name = req.body.patient_name
new_drug.drug_name = req.body.drug_name;
new_drug.dosage = req.body.dosage;
new_drug.frequency = req.body.frequency;
new_drug.adherence = req.body.adherence;
new_drug.reason = req.body.reason;
new_drug.user_id = req.user.id;
new_drug.save((err, data) => {
if (err) {
res.status(400).json({
errorMessage: err,
status: false
});
} else {
res.status(200).json({
status: true,
title: 'Drug Added successfully.'
});
}
});
} else {
res.status(400).json({
errorMessage: 'Add proper parameter first!',
status: false
});
}
} catch (e) {
res.status(400).json({
errorMessage: 'Something went wrong!',
status: false
});
}
});
The model file looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
drugSchema = new Schema( {
patient_name: String,
drug_name: String,
dosage: Number,
frequency: Number,
adherence: Number,
reason: String,
user_id: Schema.ObjectId,
}),
drug = mongoose.model('drug', drugSchema);
module.exports = drug;
it is supposed to be <field>:<value> inside your app.post method, not <field>=<value>
The new_drug.save() method is asynchronous, so it returns a promise that you can await on:
app.post("/add-drug", async(req, res) => {
//...
await new_drug.save();
})
I have the following defined in my server.js,
//server.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var userSchema = new Schema({
"userName": {
type: String,
unique: true
},
"password": String,
"loginHistory": [{
"userAgent": String,
"dateTime": Date
}]
});
var User;
module.exports.initialize = () => {
return new Promise(function (resolve, reject) {
let db = mongoose.createConnection("mongodb://<dbuser>:<dbpassword>#ds237409.mlab.com:37409/web322_a6");
db.on('error', (err)=>{
reject(err); // reject the promise with the provided error
});
db.once('open', () => {
User = db.model("users", userSchema);
resolve();
});
})
};
I have a function that is called when posting to my app.post('/register') route, and it basically builds a new User, then assigns it to the passed data, and resolves it afterwards.
module.exports.registerUser = (userData) => {
return new Promise((resolve, reject) => {
if (userData.password != userData.password2) {
reject("Passwords do not match!");
}
let newUser = new User(userData);//<!-- 'Error: TypeError: User is not a constructor'
newUser.save((err) => {
if(err.code == 11000) {
reject("Username already taken");
} else {
reject("Error creating User: " + err);
}
// exit the program after saving
//process.exit();
resolve();
});
})
}
At first I thought I've misdefined User, but I seem to have initialized it properly, as per the MongoDB documentation. Any thoughts? It keeps throwing Error: TypeError: User is not a constructor
EDIT: /post / register
app.post("/register", (req, res) => {
console.log("entering1");
dataServiceAuth.registerUser(req.body).then((data) => {
res.render('register', {successMessage: "User Created"});
}).catch((err) => {
console.log("Error: " + err);
res.render('register', {errorMessage: err, userName: req.body.userName});
})
});
My error was in,
let db = mongoose.createConnection("mongodb://<dbuser>:<dbpassword>#ds237409.mlab.com:37409/web322_a6");
The greater than and less than signs are not to be used. Proper string:
let db = mongoose.createConnection("mongodb://dbuser:dbpassword#ds237409.mlab.com:37409/web322_a6");
I have a problem. I'm trying to save answers from a survey. My problem is that I'm sending these answers through axios and they are showing in the console.log from the server, which means that my data is reaching the server safely. But data is not being saved. Also no error is shown.
Server.js
router.route('/answers')
//post answers to database
.put(function(req, res){
var survey = new Survey();
survey.name = req.body.name;
survey.email = req.body.email;
survey.q_id = req.body.q_id;
survey.q_text = req.body.q_text;
survey.answer = req.body.answer;
console.log(Survey.collection)
survey.save(function(err){
if(err){
console.log(err)
return ;
}
res.send(survey);
});
})
Survey.js (Model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var question = new Schema({
q_text:String,
order: Number,
options:[{
type: {type: String},
value: {type: String}
}]
});
module.exports = mongoose.model('Question',question);
Code that is posting the data
const url = 'http://localhost:3100/api/answers';
axios.put(url, survey)
.then(res => {
console.log('Successfully posted');
console.log(res);
setSubmitting(false);
setStatus({submitted: true});
})
.catch(err => {
console.log(err);
})
Try this :
survey.save(function(err, savedSurvey){
if(err){
console.log(err)
return ;
}
res.send(savedSurvey);
});
I'm trying to save students records, but it should not take duplicate records. How is it possible? In below code i have tried to do
app.post("/save",function(req,res){
var std=new student(req.body);
student.findOne({},function(err,success){
if(err)
{
console.log(err);
}
else
{
// console.log(success);
std.save(function(err,success){
if(err)
{
console.log(err);
}
else
{
console.log("inserted");
console.log(success);
}
});
}
})
});
Here is the sample code. Please note that the existence of the value in MongoDB database depends on the req.body as mentioned in the OP.
In the below code, I have only name attribute in the Student collection. So, the duplicate check is based on the name attribute only.
You may need to change the code if you would like to check for the specific attribute in the collection to determine the duplicate value.
Please note that my Student collection has only attribute in the schema as well.
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Student = mongoose.model('Student', { name: String });
var app = express();
var bodyParser = require('body-parser');
var app = express();
var urlencoded_body_parser = bodyParser.urlencoded({
extended: true
});
app.use(bodyParser.json());
app.use(urlencoded_body_parser);
app.post("/save", function (req, res) {
console.log(req.body);
var student = new Student(req.body);
Student.findOne(req.body, function (err, success) {
if (err) {
console.log(err);
res.send(err);
}
else {
console.log(success);
if (success == null) {
student.save(function (err, success) {
if (err) {
console.log(err);
res.send(err);
}
else {
console.log("inserted");
console.log(success);
res.send("success");
}
});
} else {
res.send("Student already present");
}
}
})
});
app.listen(3000);
Output:-
First time execution:-
Input:-
{
"name" : "john"
}
Output:-
success
Subsequent executions with the same input json:-
Output:-
Student already present
I have this code
var UserSchema = new Schema({
Username: {type: String, index: true},
Password: String,
Email: String,
Points: {type: Number, default: 0}
});
[...]
var User = db.model('User');
/*
* Function to save the points in the user's account
*/
function savePoints(name, points){
if(name != "unregistered user"){
User.find({Username: name}, function(err, users){
var oldPoints = users[0].Points;
var newPoints = oldPoints + points;
User.update({name: name}, { $inc: {Points: newPoints}}, function(err){
if(err){
console.log("some error happened when update");
}
else{
console.log("update successfull! with name = " + name);
User.find({Username: name}, function(err, users) {
console.log("updated : " + users[0].Points);
});
}
});
});
}
}
savePoints("Masiar", 666);
I would like to update my user (by finding it with its name) by
updating his/her points. I'm sure oldPoints and points contain a
value, but still my user keep being at zero points. The console prints
"update successful".
What am I doing wrong? Sorry for the stupid / noob question.
Masiar
It seems you are doing a few unstandard things:
Use findOne instead of find if you want to load just one user
Calling Model.update should be done to update records that you have not loaded
$inc is adding oldPoints, so the new value will be 2*oldPoints + newPoints
You are using name as the conditional query instead of Username
I would rewrite the code into something like this:
User.findOne({Username: name}, function(err, user){
if (err) { return next(err); }
user.Points += points;
user.save(function(err) {
if (err) { return next(err); }
});
});
follow my code guy
User.update({ username: "faibaa" },
{ $inc: { point: 200000 } }, function(err,data){
return res.send(data);
});