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'});
});
});
});
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 trying to create a many to many relationship with mongoose for when I am creating an employee. However I'm getting the following error when I call the .post:
TypeError: Employee.create(...).populate is not a function
My .get in which I also use .populate isn't throwing any errors. Which makes me wonder why .post does.
This is my code:
app.route('/api/employees')
.get(function (req, res, next) {
Employee.find()
.populate('statuses')
.exec(function (err, employee) {
if (err) {
return next(err);
}
res.json(employee);
});
})
.post(function (req, res, next) {
Employee.create(req.body)
Employee.findById(req.params._id)
.populate('statuses')
.exec(function (err, employee) {
if (err) {
return next(err);
}
res.json(employee);
});
});
This is the status class:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var statusSchema = new Schema({
name: ['In office', 'Project', 'Fired', 'Resigned', 'Ill']
});
module.exports = mongoose.model('Statuses', statusSchema);
And this is the employee class:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var employeeSchema = new Schema({
name: String,
division: ['IT','System','Trainee','Intern'],
statuses: [{type:Schema.Types.ObjectId, ref: 'Statuses'}],
project: Boolean,
comment: {type:String, default:null}
});
module.exports = mongoose.model('Employees', employeeSchema);
It seems the .post also seems to throw a 500 error, but I'm not sure if the two are related.
Is there an obvious error in above code or should I look for a mistake somewhere else?
The first thing you did wrong in the post request is that you never save the state, if the state saved then you save the status._id in the statuses.Then you do findById and find the employee._id and then you populate.
Here is an example:
Status.create(req.body, (err, status) => {
if (err) console.error(`Error ${err}`)
Employee.create({
name: req.body.name,
comment: req.body.comment,
division: req.body.division,
name: status._id
}, (err, employee) => {
if (err) console.error(`Error ${err}`)
Employee
.findById(employee._id)
.populate('statuses')
.exec((err, employee) => {
if (err) console.error(`Error ${err}`)
// console.log(JSON.stringify(employee))
res.json(employee);
})
})
})
In mongoose is not possible to populate after creating the object.
see Docs
I'm learning Angular by following this tutorial. No what I don't get is why is there two ways of saving/editing an object? They don't really explain it.
first way (in the index.js router):
router.post('/posts', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post) {
if (err) { return next(err); }
res.json(post);
});
});
second way (in the mongoose model):
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: { type: Number, default: 0 },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
PostSchema.methods.upvote = function(cb) {
this.upvotes += 1;
this.save(cb);
};
mongoose.model('Post', PostSchema);
The two ways are actually the same.
In the first example a new instance of Post is created. The save is called on this instance because it exists on PostSchema (inherited from Mongoose Schema).
In the second example we define a new method on PostSchema so when invoked, this refers to the instance of the Post.
The cb parameter is a callback which is normally a function.
Look at this example.
router.post('/posts', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post) {
if (err) { return next(err); }
var callback = function(err, post) {
console.log("Upvoted");
res.json(post);
}
post.upvote(callback);
});
});
Here a new post is created with one upvote by default.
A new instance of Post is created and saved in the db. After save, upvote method is called. After the upvote was saved in the db, the new post is returned in the response.
Hope this helps.
The first part is a normal Mongoose save in which you create a new object from the schema. The second is having a method defined in the schema to handle the save.
PostSchema.methods.upvote = function(cb) {
this.upvotes += 1;
this.save(cb);
};
For example, assuming I already have a saved post and I want to upvote it. I can have a route like this:
router.put('/post/:id/upvote', function(req, res, next) {
Post.findOne({_id: req.params.id}, function (error, post) {
post.upvote(function(error, post) {
res.json(post);
});
});
});
In simple terms, the code above makes use of the inbuilt "upvote" method that is already defined in the Schema, so all objects created from the Schema will have an "upvote" method that will increase the number of upvotes. It is the same thing as doing this:
router.put('/post/:id/upvote', function(req, res, next) {
Post.findOne({_id: req.params.id}, function (error, post) {
post.upvotes += 1;
post.save(function(error, post) {
res.json(post);
});
});
});
Just that it is cleaner and saves you a few keystrokes.
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 have this variable Blog which is a mongoose model. It gets defined here:
db.once("open", function(){
var userSchema = new mongoose.Schema({
username: String,
password: String
});
var blogSchema = new mongoose.Schema({
title: String,
content: String,
userId: String
});
User = mongoose.model("User", userSchema);
Blog = mongoose.model("Blog", blogSchema);
});
I want to use app.get to generate a url that looks like /post/blogpost_id/edit so I tried to do this:
Blog.find(function (err, posts){
app.get("/post/" + posts._id + "/edit/", checkAuth, function(req, res){
res.render("edit.html", {
pageTitle: "Edit",
pages: {
"Log Out": "/logout"
},
posts: posts
});
});
});
As you can imagine, that doesn't work. How can I fix this?
The reason is that Blog gets defined in an asynchronous callback, so your code gets further executed while node is waiting for the database to be opened and therefore will not be defined yet.
Also the defining of your route is extremely inefficient. You should define a route with a parameter: /post/:postID/edit and inside the callback check whether the post with the given ID exists. It will look like this afterwards (note that I don't know mongoose and wrote this after a quick check of the manual):
app.get("/post/:postID/edit/", checkAuth, function (req, res) {
Blog.find({ _id: req.params.postID }, function (err, posts) {
if (posts.length == 0) res.send(404, 'Not found');
else // yadayada
});
});