I'm learning mongo from absolute scratch, and i can't for the hell of it figure out how to create a collection with predefined variables. I need to do that in order to have unique mails on my project. Any help would be very appreciated.
I'm trying to do a basic CRUD, and everything you see in the code is a lot of different tutorials combined into one, so far I'm able to create new users, and obtain a list of all of them, but in order to delete one or edit/update one I really need an unique attribute.
This is my code if it is useful:
const express= require ('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const app = express();
const cors = require('cors');
const bcrypt = require('bcrypt');
const MongoClient = require('mongodb').MongoClient;
const saltRounds=10;
app.use(cors());
app.use(express.json());
app.listen(3001,()=>{
console.log("Welcome");
});
// CONEXION BASE DE DATOS
MongoClient.connect('mongodb+srv://admin:admin@cluster0.bs9d2.mongodb.net/test?retryWrites=true&w=majority'
,{ useUnifiedTopology: true }).then(client=>{
console.log('Bienvenido a database mongo');
const db = client.db('ezbuy-database');
const usersCollection = db.collection('users');
/*Añade un usuario nuevo a la BD*/
/*Falta ver como hacer datos unicos, pero no se como*/
app.post('/newuser', (req, res) => {
const userObject ={
name: req.body.name,
identification:req.body.identification,
email:req.body.email,
password:req.body.password,
cellphone:req.body.cellphone,
addedDate:req.body.addedDate,
lastLoginDate:req.body.addedDate,
role:req.body.role,
speciality:req.body.speciality
}
;
bcrypt.hash(userObject.password,saltRounds,(err,hash) => {
if(err){console.log(err)}
userObject.password=hash;
usersCollection.insertOne(userObject)
.then(result => {
console.log(result);
console.log("Dato Añadido a mongo ");
res.send('Usuario Creado');
})
.catch(error => console.error(error))
})
})
/*Devuelve todos los usuarios creados*/
app.get('/allusers', (req, res) => {
db.collection("users").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
res.send(result);
});
app.get('/userbyid',(req,res) =>{
db.collection("users").findOne({})
}
)
})
}).catch(console.error)
I'm assuming that you are referring to a database schema with create a collection with predefined variables. MongoDB does not have a strict schema that prepopulates values with defaults. That is up to your application to handle. Realm Schemas
After a document insert is completed you can read the inserted document id from the result with the result.insertedId.
MongoDB collection.insertOne()
usersCollection.insertOne(newUser)
.then(result => console.log(`Successfully inserted user with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
to fetch that user document by id you can use _id in the filter.
usersCollection.findOne({_id: userId})
-- So in the case of a user collection the normal is normally to also have a unique value that a user can remember. (email, username). In that case you need to create a unique index on the collection. MongoDB Unique Indexes
usersCollection.createIndex( { "email": 1 }, { unique: true } )
The unique flag will take care that no user with a duplicate email address gets created and you can then query the user like the following.
usersCollection.findOne({email: emailAddress})