This is model in models.js
var PatientSchema = new mongoose.Schema({
_id : String,
LastName : String,
MiddleName : String,
PatientIntId : String,
Sex : String,
Address1 : String,
City : String,
State : String,
ZipCode : String,
AccountNumber : String,
Ssn : String
});
var PatientInfoMdl = mongoose.model('PatientInfo',PatientSchema);
exports.PatientInfoMdl = PatientInfoMdl;
and my code for accessing data is :
var dbObj = require('../dataBase');
var config = require('../config');<
var moment = require('moment');
var models = require('../models/models');
var orm = require('orm');
var xml2js = require('xml2js');
var fs = require('fs');
var user = models.user;
var PatientInfoMdl = models.PatientInfoMdl;
exports.DisplayUsers = function (req, res) {
var name = '';
dbObj.connect(config.get('mongo'), function () {
PatientInfoMdl.find()({}, function (err, docs) {
if (err)
res.json(err);
else res.render('index', { Patients : docs });
});
});
}
and I am not getting data and what is my mistake?
My mistake is not following the naming conventions of collections in mongoDB.
Is there a convention to name collection in MongoDB?
For example:
Controller.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports = {
show: function(req, res) {
User.find({}, function(err, users) {
res.render('main', {users: users});
})
}
}
Models:User.js
// require mongoose
var mongoose = require('mongoose');
// create the UserSchema
var UserSchema = new mongoose.Schema({
name: String
})
// register the schema as a model
var User = mongoose.model('User', UserSchema);
module.exports = {User}
routes.js
// here we load the Quote model that we created on the server.js page
var mongoose = require('mongoose');
var User = mongoose.model('User');
// import users
var users = require('../controllers/users.js');
module.exports = function(app) {
app.get('/', function(req, res) {
res.send("Hello");
})
app.get('/user',function(req,res){
users.show(req,res);
})
}
Related
How can I execute this populate so that I can get the username of the person that does the tweet? I've tried with the function getusername() but it is not working as it gives me a tweetsSchema.findOne is not a function error.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var tweetsSchema = new Schema(
{
tweets: { type: String, required: true }, //reference to the associated book
replies: { type: String, required: false },
username: { type: Schema.Types.ObjectId, ref: 'users' }
}
);
// Virtual for bookinstance's URL
function getUsername(tweets){
return tweetsSchema.findOne({ tweets: tweets })
.populate('username').exec((err, posts) => {
console.log("Populated User " + username);
})
}
getUsername()
//Export model
module.exports = mongoose.model('tweets', tweetsSchema);
currently the function you have defined is just a function and haven't defined on the Schema of yours and not exported.
you might want to use static in mongoose
tweetsSchema.static('getUsername', async function(tweets){
return await tweetsSchema.findOne({ tweets: tweets })
.populate('username').exec((err, posts) => {
console.log("Populated User " + username);
})
})
While sending a post request i written the following code :
var email = req.body.email ;
var newDetails = { email: email };
Details.create(newDetails);
console.log(newDetails);
while sending the request. The console.log shows me the correct details,
However in the mongo shell the only collection that exist is "details" and it's empty .
That's the Mongoose Schema:
var mongoose = require("mongoose");
var DetailsSchema = mongoose.Schema({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
I'm using NodeJS.
Thanks in advance.
Your Mongoose Model should be like
const mongoose = require("mongoose");
const Scheme = mongoose.Schema;
const DetailsSchema = new Scheme({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
Node js Code should be like
var detailsModel = require('../model/Details.js');//path of mongoose model
var detailsData = new detailsModel();
detailsData.email = req.body.email;
detailsData.save(function (err, savedJob) {
if (err) {
return res.send(err);
} else {
return res.send(savedJob);
}
});
To save data in mongoDB's Database
You can use this way
var detailsData = new detailsModel();
detailsData.save()
.then(business => {
res.status(200).json({'Details': 'newDetails added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
With this, you can also handle error easily.
I'm using the plugin
mongoose-auto-increment
and it is working fine.
In the description we have to use it like this
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
autoIncrement = require('mongoose-auto-increment');
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
var bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(autoIncrement.plugin, 'Book');
var Book = connection.model('Book', bookSchema);
I have multiple models where i need to auto increment fields
Do i have to initialize in each model the below line
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
in each model file (where i need increment function)?
I share the solution i implemented myself
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var autoIncrement = require('mongoose-auto-increment');
var connection = mongoose.createConnection("mongodb://localhost/mydatabase");
autoIncrement.initialize(mongoose.connection);
exports.mongoose = mongoose;
exports.Schema = Schema;
exports.autoIncrement = autoIncrement;
and for the schema file
var mong = require('./db');
var Schema = mong.mongoose.Schema;
var autoIncrement = mong.autoIncrement;
var bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(autoIncrement.plugin, 'Book');
module.exports = mong.mongoose.model('Book', bookSchema);
I am saving an image via monngoose but I cannot find it in mongodb?
My Code
var express = require('express');
var fs = require('fs');
var app=express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imgPath = '\Adpic.jpg';
mongoose.connect('mongodb://localhost:/27017/test');
var schema = new Schema({
img: { data: Buffer, contentType: String }
});
img: { data: Buffer, contentType: String }
});
var An = mongoose.model('An', schema);
app.post('/upload',function(req,res){
var asin = new An();
asin.img.data = fs.readFileSync(imgPath);
asin.img.contentType = 'image/jpg';
asin.save(function (err, a) {
if (err) throw err;
console.error('saved img to mongo');
res.json(a);
});
});
app.listen(3000);
hi i am trying to remove a value from mongoDB but instead of removing a specific value the code is deleting all users from the schema lol.
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.unfollow = function(req, res){
var thefollowee = req.body.followee;
var thefollower = req.body.follower;
User.find({_id: thefollower}).remove({following: thefollowee}).exec();
User.find({_id: thefollowee}).remove({followers: thefollower}).exec();
res.json({ message: 'Unfollowed'});
};
the followee is pointing to the id of the person being followed,
the follower is pointing to the id of the user who follows the followee.
ok so i got it by using the $pull method
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.unfollow = function(req, res){
var thefollowee = req.body.followee;
var thefollower = req.body.follower;
User.findByIdAndUpdate(thefollowee, { $pull: { followers: req.body.follower }}, function (err, user) {
if (err)
return handleError(err);
});
User.findByIdAndUpdate(thefollower, { $pull: { following: req.body.followee }}, function (err, user) {
if (err)
return handleError(err);
});
res.json({ message: 'Unfollowed'});
};