update a document using mongodb by the Id of the document - mongodb

how to update a document using mongodb by the Id of the document, this is what I tried to do:
I am retrieving the document with the given id from the db,
then construct a new user with the information provided by the user
and update the userinformation to the db.
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, async function (err, db) {
console.log(args);
if (err) throw err;
var dbo = db.db("UserApp");
//retrieve the document with the given id from the db
let user = await dbo
.collection("users")
.findOne({ _id: ObjectId(args.id) }, function (err, result) {
if (err) throw err;
console.log(result);
});
const myquery = { name: user.name };
// construct a new user with the information provided by the user
const newuser = new User({
name: args.name,
title: args.title,
email: args.email,
});
// update the userinformation to the db
dbo.collection("users").updateOne(myquery, newuser, function (err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});

Related

How do i insert data in MongoDB from node.js from form

Hi I am trying to make a registration form and i want to store data to MongoDB with node.js and from node.js I want to request an HTML form the email and password and then store that data to MongoDB.
Anyone know how?
To get info from the form using mongoose(MongoDB) and node.js you do:
const mongoose = require('mongoose');
mongoose.connect(mongoString, { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: String,
password: String
});
const User = mongoose.model('users', userSchema);
app.post('/register', async (req, res, next) => {
const user = await User.findOne({
email: req.body.email
})
if (user) {
res.redirect('/register');
} else {
bcrypt.genSalt(10, function (err, salt) {
if (err) return next(err);
bcrypt.hash(req.body.password, salt, function (err, hash) {
if (err) return next(err);
new User({
email: req.body.email,
password: hash
}).save()
req.flash('error', 'Account made, please log in.');
res.redirect('/login');
});
});
}
});

How to find all users except current user with Mongoose

I am trying to display a list of users but the logged-in user shouldn't see himself in the list. I can't make the request to get all users but current user to work.
router.get("/", auth, async (req, res) => {
try {
const users = await User.find({ user: { $ne: req.user.id } }).select([
"email",
"username",
"bio"
]);
res.json(users);
} catch (err) {
console.error(err.message);
res.status(500).send("Servor Error");
}
});
module.exports = router;
This request below gets the current user and it works.
router.get("/", auth, async (req, res) => {
try {
const user = await User.findOne({
user: req.user.id
});
if (!user) {
return res.status(400).json({ msg: "There is no profile for this user" });
}
res.json(user);
} catch (err) {
console.error(err.message);
res.status(500).send("Servor error");
}
});
module.exports = router;
You need to use _id field inside the query filter instead of user:
const users = await User.find({ _id: { $ne: req.user.id } }).select([
"email",
"username",
"bio"
]);

unable to populate documents using mongoose populate()

I am making an application in express using mongoose. I have a collection called users in which there is a filed called _subscriptions, which is an array of objects and each object contains a field named field which is an ObjectId for the documents of fields (this is another collection in my db).
I want to make such an API which after getting id parameter returns me a user form users collection with field attribute populated instead of its id in value of the field field. For this I am using populate method but it is not working.
This is screenshot showing users collection:
This is screenshot showing fields collection:
This is schema for field (File name Field.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FieldSchema = new Schema(
{
_id: Schema.Types.ObjectId,
name: String,
price: Number,
_categories: [{
type: Schema.ObjectId,
}],
}
);
module.exports = mongoose.model('Field', FieldSchema);`
This is schema and model for users
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
_id: Schema.Types.ObjectId,
salt: String,
provider: String,
name: String,
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
_subscriptions: [{
field: {
type: mongoose.Schema.ObjectId,
ref: 'Field',
},
status: String,
dateSubscribed: Date,
payments: [{}]
}],
role: String,
});
module.exports = mongoose.model('User', UserSchema);
This is code for user router
var Field = require('../model/Field');
var express = require('express');
var router = express.Router();
var User = require('../model/User');
router.get('/',function(req, res, next) {
User.find({}, function(err, result) {
if (err) {
console.log(err);
res.send('something wrong');
}
res.status(200).send(result);
}).populate( '_subscriptions.field').exec(function (err, story) {
if (err) return handleError(err);
console.log('Here!!!!!');
});
});
router.get('/findById/:id',function(req, res, next) {
var id = req.params.id;
User.findById(id, function(err, doc) {
if (err) {
console.error('error, no entry found');
}
res.status(200).send(doc);
}).populate('field').exec(function (err, story) {
if (err) return handleError(err);
console.log('Here!!!!!');
});
});
router.get('/getSubscriptions/:id',function(req, res, next) {
var id = req.params.id;
User.findById(id, function(err, doc) {
if (err) {
console.error('error, no entry found');
}
var type = typeof(doc);
res.status(200).send(doc);
})
});
module.exports = router;
This is where I have called app.use method:
And this is response I am getting using postman
I am looking forward for someones' assistance in resolving this issue
as i am unable to identify my mistake. Your help in this regard will be highly appreciated.
Thanking in advance
What I have understood is, In the user collection, there is _subscriptions and in _subscriptions, there is field. If this is your schema, then you should pass "_subscriptions.field" as a parameter to the populate function not "field" as you have passed currently.
So, your code for user's sub route, /findById/:id, must be like this:
router.get('/findById/:id',function(req, res, next) {
var id = req.params.id;
User.findById(id, function(err, doc) {
if (err) {
console.error('error, no entry found');
}
res.status(200).send(doc);
}).populate('_subscriptions.field').exec(function (err, story) {
if (err) return handleError(err);
console.log('Here!!!!!');
});
});

unable hash the password in mean stack

This is the code from routes file.
router.put('/reset/:token', function(req, res, next) {
console.log('reseting the password');
User.findOne({resetPasswordToken:req.params.token}, function(err, user) {
if(err) {
return next(err);
}
if (!user) {
return res.status(422).json({errors: [{msg: 'invalid reset token'}]});
}
user.resetPasswordToken ='';
user.resetPasswordExpires = '';
user.password = req.body.password;
User.addUser(user, (err, user) => {
if(err){
res.json({success: false, msg:'password has not changed'});
} else {
res.json({success: true, msg:'password has changed'});
}
});
});
});
This part of the code is from my schema file.
const UserSchema = mongoose.Schema({
password: {
type: String,
required: true
},
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
}
});
const User = module.exports = mongoose.model('User', UserSchema);
module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
});
});
}
When I try to rest the password it is storing as I've given the input. It is not hashing the password. For example, I have given the password as "zp12345", in the database it is storing as "password" : "zp12345".
For solve the problem you need to fix your addUser method:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
module.exports.addUser = function(newUser, callback){
bcrypt.hash(newUser.password, bcrypt.genSaltSync(10), null, (err, hash) => {
if (err) {
return next(err);
}
newUser.password = hash;
newUser.save(callback);
})
};
Here there is another example: Mongoose Pre Save Changing Password
And this is the library documentation: Bcrypt Nodejs

How to connect to mongoLab?

I developed a simple MEAN stack CRUD app. I deployed my site to azure websites. In my localhost the app work fine. But I want to connect with mongoLab database. How can I connect it?
This is the code for server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('posts', ['posts']);
var bobyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bobyParser.json());//
app.get('/posts', function (req, res) {
console.log("I got the server request!")
db.posts.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/posts', function (req, res) {
console.log(req.body);
//Insert - This is the first part of the CRUD
db.posts.insert(req.body, function (err, doc) {
res.json(doc);
});
});
app.delete('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.posts.remove({ _id: mongojs.ObjectId(id) }, function (err, doc) {
res.json(doc);
});
});
app.get('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.posts.findOne({ _id: mongojs.ObjectId(id) }, function (err, doc) {
res.json(doc);
});
});
app.put('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(req.body.name);
db.posts.findAndModify({
query: { _id: mongojs.ObjectId(id) },
update: { $set: { name: req.body.name, info: req.body.info, twitter: req.body.twitter }},
new: true
}, function (err, doc) {
res.json(doc);
});
});
app.listen(3000);
console.log("Server running from port 3000");
How can I make the connection? I have the connection info what azure provides.
Thanks a lot.
Can you look at the exact Exception error message?
Try something like the following:
try
{
smtp.Send(msg);
Response.Write("<script>alert('Mensaje enviado correctamente');</script>");
NullTextBox();
}
catch (Exception ex)
{
Response.Write(string.Format("<script>alert('There is an error on connection to DB on microsoft azure:{0}');</script>", ex.ToString()));
NullTextBox();
}