'Im trying to have an array of patients Objectids and an array of data(information about doctor) objectids inside the doctors collection. This is the beginning of the code then I got lost. I think I want to use something like this Doctor.find().populate('patients data'). Then if someone could show me how to access the information that would be great.
var express = require("express");
var app = express();
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/population")
var doctorSchema = new mongoose.Schema({
name : String,
patients : [{type : mongoose.Schema.Types.ObjectId, ref : "Patient"}],
data : [{type : mongoose.Schema.Types.ObjectId, ref : "Data"}]
})
var patientSchema = new mongoose.Schema({
name : String
})
var dataSchema = new mongoose.Schema({
income : String
})
var Doctor = mongoose.model("Doctor",doctorSchema );
var Patient = mongoose.model("Patient", patientSchema);
var Data = mongoose.model("Data", dataSchema);
var doc1 = new Doctor({"name" : "doc1"})
doc1.save(doc1, function(err, doc){
if(err){
console.log(err)
}else{
console.log("saved")
}
})
app.listen(3000, function(){
console.log("listening on 3000");
})
To access the information, the app should be able to receive requests; a 'get' method needs to be defined on the app object:
app.get('/:id', function(req, res) {
var doctorID = req.params.id;
Doctor
.findOne({_id: doctorID})
.populate('patients data')
.exec(function(err, doctor) {
if (err) throw err;
res.send(doctor);
});
});
Related
I'm trying to write an endpoint for an API that will return all orders for a given user. My issue is that when I try to query the database using mongoose's findById function, the 'user' object is undefined in the callback function and I can't query the orders subdoc. To add to the confusion, I can get it to work if I don't use a callback function, but then I don't have proper error handling.
var mongoose = require('mongoose');
var router = express.Router();
var order_model = require('../models/order');
var user_model = require('../models/user');
router.get('/:userid/order/', function (req, res) {
// This works???
var u = user_model.findById(req.params.userid);
res.json(u.orders);
});
The following code throws the error "TypeError: Cannot read property 'orders' of undefined".
var mongoose = require('mongoose');
var router = express.Router();
var order_model = require('../models/order');
var user_model = require('../models/user');
router.get('/:userid/order/', function (req, res) {
// This throws an error.
user_model.findById(req.params.userid).then(function (err, user) {
if (err) {
res.send(err);
}
res.json(user.orders);
});
});
user.js
var mongoose = require('mongoose');
var ordersSchema = require('./order').schema;
var userSchema = new mongoose.Schema({
name: String,
email: String,
showroom: String,
orders: [ordersSchema]
});
module.exports = mongoose.model('User', userSchema);
order.js
var mongoose = require('mongoose');
var lineItemsSchema = require('./lineitem').schema;
var ordersSchema = new mongoose.Schema({
trackingNumber: Number,
lineItems: [lineItemsSchema]
});
module.exports = mongoose.model('Order', ordersSchema);
Any help / explanation of this behavior would be appreciated. Thanks!
The first parameter of the then callback is user, not err.
Either use a traditional callback:
user_model.findById(req.params.userid, function (err, user) {
if (err) {
res.send(err);
return; // Need to return here to not continue with non-error case
}
res.json(user.orders);
});
Or chain a call to catch on the promise to separately handle errors:
user_model.findById(req.params.userid).then(function (user) {
res.json(user.orders);
}).catch(function(err) {
res.send(err);
});
I usually query like this, it work perfect :
user_model.find(_id : req.params.userid)
.exec((err, user) => {
if(err){
//handle error
}
return res.status(200).json(user.orders);
})
});
I'm try to fetch data from mongoDB using this code in node.js, but It's not working even not show any error or result. I have already test DB, there is lots for data available like [Database output]
{
"_id" : ObjectId("597321311e13c57335727a6d"),
"name" : "Amanda",
"publisher" : "MTV india"
}
{
"_id" : ObjectId("5973220b1e13c57335727a6e"),
"name" : "Deepka",
"publisher" : "MTV"
}
{
"_id" : ObjectId("597322141e13c57335727a6f"),
"name" : "sunil",
"publisher" : "MTV india"
}
app.js
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
var booksDetail = require('./modal/book');
var url = "mongodb://localhost:27017/example";
// Connect to the db
MongoClient.connect(url);
app.get('/api/books', function(req,res) {
res.send("on book page");
booksDetail.find({})
.exec(function(err, books) {
console.log("--working--");
if(err) {
res.send('error occured')
res.send('error occured')
} else {
console.log(books);
res.json(books);
}
});
});
app.get('/api/school', function(req,res){
res.send('hello this is school page');
});
app.listen(7900);
console.log('server is runing 7900')
modal/book.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bookSchema = new Schema({
name: {
type: String,
requierd: true
},
publisher : {
type: String,
requierd: true
}
})
module.exports = mongoose.model('booksDetail', bookSchema);
You haven't connected to your MongoDB server (using mongoose) yet.
Choose to use either mongoose or mongodb library, not both. Check it docs carefully.
you load mongo and mongoose but you connect using mongo and your document is stored with mongoose. So just remove mongo and connect with mongoose
mongoose.connect('mongodb://localhost:27017/example');
var db = mongoose.connection;
db.once('open', function() {
console.log('OPEN');
});
I am developing a web app using nodejs, angular, mongo. Having a weird problem. Model is not binding properly from json object.
this is my Schema.
var mongoose = require('mongoose');
var productSchema = new mongoose.Schema({
name : {type: String},
imageURL : {type: String, default: '/'},
created : {type: Date, default: Date.now}
});
module.exports = mongoose.model('product', productSchema);
And I am passing the product using POST to my index.js.
router.post('/pictures/upload', function (req, res, next) {
uploading(req, res, function(err){
if (err) {
console.log("Error Occured!");
return;
}
var product = new productModel(req.body.pName);
product.imageURL = req.file.path;
product.update(product);
res.status(204).end();
});
var product only consists of _id, created, imageURL. not the name property.
But console.log(req.body.pName) prints out {"_id":"56d80ea79d89091d21ce862d","name":"sunny 2","__v":0,"created":"2016-03-03T10:15:03.020Z","imageURL":"/"}
Its not getting the name property. Why is that???
Please advise.
Found the Solution. It wasn't binding properly because content-type was in multipart/form-data. I had to parse the jSON object, like this:
var product = new productModel(JSON.parse(req.body.pName));
pName had the values in a string.
Hope this helps someone.
Try this way, You just creating instance of Product object and then updating.
var Product = mongoose.model('products');
uploading: function(req, res) {
// console.log(req.body); find your object
// in your case it looks req.body.pname
var product = new Product(req.body.pname);
product.imageURL = req.file.path;
product.save(function (err, product) {
if (err){
console.log(err);
}else{
res.status(204).end();
// it returns json object back - callbcak
// res.json(product);
}
})
},
I am currently attempting to create a .post function for a schema with document reference. However, I am not sure how I can retrieve the ObjectID of the document reference from another collection.
Board.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
boardname: String,
userid: {type: Schema.ObjectId, ref: 'UserSchema'}
});
module.exports = mongoose.model('Board', BoardSchema);
User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String
});
module.exports = mongoose.model('User', UserSchema);
routes.js
router.route('/boards')
.get(function(req, res) {
Board.find(function(err, boards) {
if(err)
res.send(err);
res.json(boards);
});
})
.post(function(req, res) {
var board = new Board();
board.boardname = req.body.boardname;
User.find({username: req.body.username}, function(err, user) {
if(err)
res.send(err);
board.userid = user._id;
});
board.save(function(err) {
if(err)
res.send(err);
res.json({message: 'New Board created'});
});
});
To create the board, I include a boardname and a username in my request. Using the username, I do a User.find to find the specific user and assign it to board.userid. However, this does not seem to be working as board.userid does not appear.
Any help would be greatly appreciated!
Thank you!
EDIT
A better explanation of what is required is that I have an existing User collection. When I want to add a new document to Board, I would provide a username, from which I would search the User collection, obtain the ObjectId of the specific user and add it as userid to the Board document.
I believe you are looking for population
There are no joins in MongoDB but sometimes we still want references
to documents in other collections. This is where population comes in.
Try something like this:
//small change to Board Schema
var BoardSchema = new Schema({
boardname: String,
user: {type: Schema.ObjectId, ref: 'User'}
});
//using populate
Board.findOne({ boardName: "someBoardName" })
.populate('user') // <--
.exec(function (err, board) {
if (err) ..
console.log('The user is %s', board.user._id);
// prints "The user id is <some id>"
})
Sorry, I solved a different problem previously. You'll probably want to use the prevoius solution I provided at some point, so I'm leaving it.
Callbacks
The reason the userid is not on the board document is because User.find is asynchronous and is not assigned at the moment board.save(...) is called.
This should do the trick:
(Also, I added a couple of returns to prevent execution after res.send(...))
.post(function(req, res) {
var board = new Board();
board.boardname = req.body.boardname;
User.find({username: req.body.username}, function(err, user) {
if(err)
return res.send(err); //<-- note the return here!
board.userid = user._id;
board.save(function(err) {
if(err)
return res.send(err); //<-- note the return here!
res.json({message: 'New Board created'});
});
});
});
I am trying to create a User list when user submit their details. In app.js I have the function for that.
like this:
app.post('/addList', userList.submit);
I am calling my function which is nested in userList.submit:
var sendList = require('../model/model');
exports.list = function(req, res){
res.send("respond with a resource this is from list file");
};
exports.addList = function(req, res, next){
res.render('index', {title:'title from list.js'});
};
exports.submit = function(req,res,next){
var name = req.body.name,
dept = req.body.dept;
sendList.create({
name:name,
dept:dept
}, function(error){
console.log('Erros is ', error);
if (error) return next(error);
res.redirect('/');
});
};
In the model folder, model.js has the function as follows:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user_list');
var schema = new Schema({
name:String,
dept:String
});
module.exports = mongoose.model('User', schema);
But I am getting error saying:
var schema = new Schema({
^
ReferenceError: Schema is not defined
What is this mean? where I made the mistake? any one figure out and help me to solve this?
Schema is defined as a property of mongoose. It's not there in the global scope of nodejs.
var schema = new mongoose.Schema({
name:String,
dept:String
});
Schema is part of an application or is a property of mongoose. It has nothing to do with db, it's only mapping db into js objects.
you have to change the code : = new mogoose.schema ({ what ever you want ..