file user.js
const mongoose = require("mongoose");
const User = new mongoose.Schema({
name: String,
age: Number,
});
module.exports = mongoose.model("user", User);
app.js which I run database and connect
app.post("/createUser", async (req, res) => {
try {
//console.log(req.body);
const myUser = new User(req.body);
const saveUser = await myUser.save();
res.send(myUser);
} catch (err) {
res.status(500).json(err);
}
});
I try to add data in postman:{"name":"Ngan", "age":21}, but it displays fail
Related
App.js file->Connection is established successfully, but in find() callback,data is empty[]
const express = require('express');
const mongoose = require('mongoose');
const Users = require('./users');
const app = express();
mongoose.connect("mongodb+srv://sanjeev:**pass**#cluster0.ckywrym.mongodb.net?retryWrites=true&w=majority/sanjeevDb",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log("connection established successfully"));
Within find callback I am getting empty array in data
Users.find({}, (error, data) => {
if (error)
console.log("Error: ", error);
console.log(data)
});
users.js - defining the schema as same on mongoDb Atlas
const mongoose = require('mongoose');
let userSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
email: String,
country: String
});
module.exports= mongoose.model('userCollect', userSchema);
enter image description here
you are logging data even when there is error. do this
Users.find({}, (err, data) => {
if (err){
console.log(err);
} else {
console.log(data);
})
or
//with async (recommended)
try {
const users = await Users.find({});
console.log(users);
} catch (err) {
console.log(err);
}
I am a frontend developer. A colleague has kindly built me a MongoDB/Cosmos database in Azure and allowed me to retrieve a single record into my frontend. He has since gone on holiday with no cover.
(I am confused what type of database it is, since it says Azure Cosmos DB in Azure portal, but all the code in my server.js file refers to a MongoDB.) Server.js:
const express = require('express');
const app = express();
const url = 'mongodb://blah.azure.com';
app.use(express.static('static'));
const mongoClient = require('mongodb').MongoClient
let db;
app.listen(process.env.PORT || 3000, async () => {
console.log('App listening on port 3000!')
const connect = await mongoClient.connect(url)
db = connect.db('ideas');
});
app.get('/api/ideas/:name', async (req, res) => {
return res.json(await db.collection('container1').findOne({key: req.params.name}));
});
I want to retrieve all documents in this database. They each have an ID. But my colleague seems to have defined an API by name. From the MongoDB docs I can use the command find({}) instead of findOne({key: req.params.name}) to return all records, but this does not work (i.e. I get no output to the console). I presume this is because of the '/api/ideas/:name'.
I have also tried:
db.open(function(err, db){
var collection = db.collection("container1");
collection.find().toArray(function(err2, docs){
console.log('retrieved:');
console.log(docs);
})
})
but i get an error that tells me I can't retrieve the property "open" of undefined.
Can anyone help me either: (1) work out how to change the API in Azure, or (2) rewrite this code to retrieve all records? I will also need to edit and insert records. Thanks
If you want to retrive data from Mongo DB in nodejs espresso application, I suggest you use the package mongoose.
For example
Create mongo.js file to add connection details
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const accountName= 'testmongo05',
const databaseName= 'test',
const key= encodeURIComponent(''),
const port: 10255
const mongoUri = `mongodb://${env.accountName}:${key}#${accountName}.documents.azure.com:${port}/${databaseName}?ssl=true`;
function connect() {
mongoose.set('debug', true);
return mongoose.connect(mongoUri, {
useFindAndModify : false,
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
});
}
module.exports = {
connect,
mongoose
};
Define models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
userId: {
type: String,
required: true,
unique: true
},
name: String,
saying: String
},
{
collection: 'Users'
}
);
const User = mongoose.model('User', userSchema);
module.exports = User;
CURD operations
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./module/user');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
require('./mongo').connect().catch(error => console.log(error));
//list users
app.get('api/users', async (req, res) => {
const docquery = User.find({});
await docquery
.exec()
.then(users => {
res.status(200).json(users);
})
.catch(error => {
res.status(500).send(error);
});
});
// get user by userId
app.get('/api/user/:uid', async (req, res) => {
const docquery =User.findOne({userId:req.params.uid })
await docquery
.exec()
.then(user => {
if (!checkFound(res, user)) return;
res.status(200).json(user);
})
.catch(error => {
res.status(500).send(error);
});
});
// create
app.post('/api/user', async (req, res) => {
const originalUser= { userId: req.body.userId, name: req.body.name, saying: req.body.saying };
const user = new User(originalUser);
await user.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json('User created successfully!');
console.log('User created successfully!');
});
});
//update user by userId
app.put('/api/user/:uid', async (req, res) => {
const docquery =User.findOneAndUpdate({userId: req.params.uid}, req.body)
await docquery.exec()
.then((user) =>{
if (!checkFound(res, user)) return;
res.status(200).json("User update successfully");
console.log('User update successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
//delete user by userId
app.delete('/api/user/:uid', async (req, res) => {
const docquery = User.findOneAndRemove({userId: req.params.uid })
await docquery.exec()
.then(user =>{
if (!checkFound(res, user)) return;
res.status(200).json("user deleted successfully!");
console.log('user deleted successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
function checkFound(res, user) {
if (!user) {
res.status(404).send('user not found.');
return;
}
return user;
}
Test
a. Create user
b. get user
c. List Users
d. Update User
e delete user
When i wanna save a user with this code:
const router = require("express").Router();
const User = require("../model/User");
//validate
const joi = require("#hapi/joi");
const schema = joi.object({
name: joi.string().min(1).max(255).required(),
email: joi.string().max(255).email().required(),
password: joi.string().min(8).max(255).required(),
});
router.post("/register", async (request, respond) => {
const { error } = schema.validate(request.body);
if (error) return respond.status(400).send(error.details[0].message);
const user = new User({
name: request.body.name,
email: request.body.email,
password: request.body.password,
});
try {
const savedUser = await user.save();
respond.send(savedUser);
} catch (err) {
respond.status(500).send(err);
}
});
module.exports = router;
it doesnt get any error but it also does not respond anything and does not save anything
I don't see any client connection in your code. Don't forget to connect to your mongoDB server and open your connection before processing any operation. Otherwise it won't have any effect.
var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open((err, db) => {
// Do what you want
});
See this example of saving a document in nodeJS: Save to MongoDB
I make an axios request from the frontend through node to a Mongodb database requesting a userName based on userId. The request comes back as having been made, but no data is returned.
This is the Mongodb users collection:
{
"_id" : ObjectId("5e1b46cb2e6f4c98904598b0"),
"userId" : "foo#baz.com",
"userName" : "Fool",
}
This is the 'Users' schema file
users model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userId: String,
userName: String,
});
module.exports = mongoose.model('Users', UserSchema);
This is the backend request:
backend:
const express = require('express');
const UserRoute = express.Router();
const Users = require('../Models/UserModel');
UserRoute.route('/fetchUserName').get(function (req, res) {
Users.find({userId: req.query.userId}, {userName: 1})
.exec(function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
console.log(user.data);
res.json(user.data);
}
});
});
Here is the actual request from the frontend:
getUserName = () =>
axios.get('http://localhost:4000/Users/fetchUserName', {params: {userId: 'foo#baz.com'}})
.then(res => {
return res.data;
});
};
res.data is returned as an empty string.
Any ideas why the request does not work.
The userId should probably send as a string.
So either:
const params {
userId: 'foo#baz.com'
}
axios.get('http://localhost:4000/Users/fetchUserName', { params })
or
axios.get('http://localhost:4000/Users/fetchUserName', {params: {userId: 'foo#baz.com'}})
I've come across a blocker on attempting to promisify a mongoose method.
As far as my understanding goes I should be able to promisify fn's that take in callbacks with an error and a parameter, but in this case I get this error:
TypeError: this.Query is not a constructor
model code:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('User', new Schema({
name: String,
password: String,
admin: Boolean
}));
breaking code:
var User = require('./app/models/user');
var { promisify } = require('util');
var findUserPromise = promisify(User.findOne);
...
findUserPromise({ name: req.body.name })
.then(user => console.log("do something with the user"))
.catch(err => { console.log("err ", err) });
Any help is very much appreciated!
mongoose is already very promise-friendly. To get a promise from findOne(), you just need to call .exec():
Instead of
var findUserPromise = promisify(User.findOne);
...
findUserPromise({ name: req.body.name })
.then(user =>
...
Just call it with .exec()
:
User.findOne({ name: req.body.name }).exec()
.then(user =>
...
Yes as #Jim B answer, mongoose is promise friendly. you can also use async and await
const User = require('./app/models/user');
module.export = {
userDetails: async (req, res, next) => {
try {
const user = await User.findOne({ name: req.body.name });
console.log(user);
}
catch(err) {
console.log(err);
}
}
}