This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 4 years ago.
I have a user schema including a few sub-schemas. I have 2 similar sub-schemas, one of them is recognised but the other one is undefined all the time.
my user schema is as follows:
var UserSchema = new Schema({
company: String,
resetPasswordToken: String,
resetPasswordExpires: Date,
isAdmin: {type: Boolean, default: false},
projects: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Project",
}
],
trackers: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Tracker",
}
],
});
In the above schema, I have projects that is working very well in a post route . The form gets posted, saved and shown properly but the same route for trackers cannot be posted and give "trackers is undefined" error:
project post route:
app.post("/myprojects", function(req,res){
User.findById(req.user._id, function(err, user){
if(err){
console.log(err);
}else{
var pname = req.body.pname;
var pnumber = req.body.pnumber;
var newProject = {
pname:pname,
pnumber:pnumber,
};
Project.create(newProject, function(err, project){
if(err){
console.log(err);
}else{
user.projects.push(project);
user.save();
res.redirect("/myprojects");
}
});
}
});
});
Here is the tracker post:
app.post("/tracker", function(req,res){
User.findById(req.user._id, function(err, user){
if(err){
console.log(err);
}else{
var tname = req.body.tname;
var tnumber = req.body.tnumber;
var newTracker = {
tname:tname,
tnumber:tnumber,
};
Tracker.create(newTracker, function(err, tracker){
if(err){
console.log(err);
}else{
user.trackers.push(tracker);
user.save();
res.redirect("/tracker");
}
});
}
});
});
Please note both projects schema and tracker schemas are saved in a model folder and been required in app.js
photo of the error:
It must be giving you undefined because trackers is not saved in database on user object. You can use the following to fix the problem.
user.trackers = user.trackers || [];
user.trackers.push(tracker);
Related
I am trying to learn one to many relationship in MongoDB using mongoose and expressjs. I am trying to use reference method in which only id is stored as a reference.
User has already been created. Here is my code -
var mongoose = require("mongoose");
//saving application name in mongodb and connecting to it
mongoose.connect("mongodb://localhost/blog_demo_3");
//POST - title, content
var postSchema = mongoose.Schema({
title: String,
content: String
});
var Post = mongoose.model("Post", postSchema);
//USER - name email
var userSchema = mongoose.Schema({
email: String,
name: String,
//linking to many posts specific to user one to many relation
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
}
]
});
var User = mongoose.model("User", userSchema);
Post.create({
title: "How to cook burger pt 2",
content: "blah blah blah"
}, function(err, post){
User.find({name: "Bob Fischer"}, function(err, foundUser){
if(err)
console.log(err);
else {
//foundUser.posts.pus(post) - doesn't works
foundUser.posts.push(post._id);
foundUser.save(function(err, data){
if(err)
console.log(err)
else
console.log(data);
});
}
});
});
// User.create({
// email: "bob#foodtech.com",
// name: "Bob Fischer"
// }, function(err, createdBlog){
// if(err)
// console.log(err);
// else
// console.log(createdBlog);
// });
Please help. Thanks.
I'm sorry for not noticing such small syntax error.
User.find({name: "Bob Fischer"}, function(err, foundUser){
should be
User.findOne({name: "Bob Fischer"}, function(err, foundUser){
I am using Mongoose/MongoDB and I am trying to associate many comments to one article. My app begins by scraping from a website and then the user has the option to save each article that was scraped into the MongoDB. When the user chooses to save one article, I save it into database. So when a user clicks on one of their saved articles, they can comment on them. Each article has its own comment section I need to retrieve the correct comments.
//My post comment request in JS file
function postComment(){
var articleComment = {
comment: $('#comment').val().trim()
}
$.post('/comments/' + articleID, articleComment).done(function(data){
$('.main-popup').fadeOut();
console.log('DONNE', data);
});
}
//Post route in controller
router.post('/comments/:id', function(req, res){
var newComment = new Comment(req.body);
newComment.save(function(err, doc){
if(err){
console.log(err);
}else{
Comment.findOneAndUpdate({ "_id": doc._id }, { "article": req.params.id }).exec(function(err, doc){
if(err){
console.log(err);
res.send(err);
}else{
res.send(doc);
}
});
}
});
});
//Get request to get correct comments when clicked on specific article
function showCommentBox(){
$('.comments').empty();
$('#comment').val("");
articleID = $(this).attr('data-article-id');
$.get('/comments/' + articleID, function(data){
if(data.article){ //This is undefined*********************
for(var x = 0; x < data.comment.length; x++){
$('.comments').append("<div><h2>" + data.comment[x].comment + "</h2><span><button>×</button></span></div>");
}
}
$('.main-popup').fadeIn();
});
}
//Get route in controller
router.get('/comments/:id', function(req, res){
Comment.findOne({ "article": req.params.id }).populate("article").exec(function(err, doc){
if(err){
console.log(err)
}else{
res.json(doc);
}
});
});
//Article Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: {
type: String
},
link: {
type: String
},
description: {
type: String
},
img: {
type: String
}
});
var Article = mongoose.model("Article", ArticleSchema);
module.exports = Article;
//Comment Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
comment: {
type: String
},
article: {
type: Schema.Types.ObjectId,
ref: 'Article'
}
});
var Comment = mongoose.model('Comment', CommentSchema);
module.exports = Comment;
First, you're missing $set when you do .findOneAndUpdate. Also I think you should convert a string to Mongo ObjectId before setting it.
So it might look likt this:
const ObjectId = mongoose.Types.ObjectId;
Comment.findOneAndUpdate({ "_id": doc._id }, {$set: {"article": new ObjectId(req.params.id) }})
Also you don't need to make 2 database calls. You could article id before saving newComment and then simply send it as a response like this:
//Please notice that mongoose.Schema.Types.ObjectId and mongoose.Types.Object are different types.
//You need this one here:
const ObjectId = mongoose.Types.ObjectId;
router.post('/comments/:id', function(req, res){
var newComment = new Comment(req.body);
newComment.article = new ObjectId(req.params.id);
newComment.save(function(err, doc){
if (err) {
console.error(err);
res.send(err);
return;
}
res.send(doc);
});
});
I'm fairly new to Mongoose and don't think my approach on deleting an item in a subdocument is the right one.
I have the following schema setup:
//DEPENDENCIES
var mongoose = require('mongoose');
var contactSchema = new mongoose.Schema({
name:{type:String},
age:{type:Number}
});
var phoneSchema = new mongoose.Schema({
number:{ type: String },
phoneType:{ type: Number }
})
var memberSchema = new mongoose.Schema({
firstname: {
type: String
},
lastname: {
type: String
},
phone:[phoneSchema],
contacts:[contactSchema]
});
//RETURN MODEL
module.exports = mongoose.model('member', memberSchema);
To remove an item from the phone, in my Express API, I first find the parent then reference "remove" for the child ID, like this. But it does not work.
router.route('/owner/:ownerId/phone/:phoneId')
.delete(function(req, res){
Member.findOne({_id: req.body.ownerId}, function(err, member){
member.phone.remove({_id: req.body.phoneId}, function(err){
if(err)
res.send(err)
res.json({message: 'Success! Phone has been removed.'})
});
});
});
Figured out that I was looking for req.body and was actually needing req.params.
Also found right syntax on Mongoose docs:
router.route('/owner/:ownerId/phone/:phoneId')
.delete(function(req, res){
Member.findOne({_id: req.params.ownerId}, function(err, member){
member.phone.id(req.params.phoneId).remove();
member.save(function (err) {
if (err) return handleError(err);
console.log('the sub-doc was removed');
});
});
});
I have following mongodb/mongoose data model::
var UserSchema = new Schema({
name: String
, roles: [] // admin or client
/* others object */
});
mongoose.model('User', UserSchema);
var ReviewSchema = new Schema({
title: String
, user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Review', ReviewSchema);
Now I want to get all review where user's role is admin. I have tried the following way:
Review
.find( { 'user.roles': 'admin' } )
.populate('user')
.exec(function(err, review) {
console.log("review : ", review); // null
});
NB: "mongoose": "^4.2.9",
How can I solve this problem? Thanks in advance.
I hope, this code may be solved your problem
Review.find()
.populate('user', null, { roles:"admin" })
.exec(function (err, review) {
if(err) {
console.log(err);
res.json(err);
}else {
var review = review.filter(function (review) {
return review.user !== null;
}).pop();
console.log(review);
res.json(review);
}
});
I want to write a rest api, with which i am able to download some data. All datas were stored in a mongodb. I don't know what to pass to the download method, to make it possible.
Here is my current code:
router.get('/download/:productId/:username/:token', function (req, res) {
var auth = require('../provider/authProvider.js');
var authInst = new auth();
authInst.checkAuth(req.params.username, req.params.token, res, function (err, obj) {
if (obj == true) {
res.status(200);
// here is my problem, what to pass to the download-method
res.download('');
}
});
});
I could not find anything else, than passing paths to the download method.
Does anyone has an idea how to solve my problem?
I assume you know how to set up mongoose environment, putting config, connecting to MongoDB. If not please refer to my answer here.
Now let's say we have a Document in MongoDB as Blog.
So we need to create a model for Blog so that we can do CRUD operations using Mongoose ORM.
you need mongoose module for this to be included in your project.
so run this command from your project root directory, it will automatically download mongoose for you.
npm install mongoose --save
BlogModel.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var BlogSchema = new Schema({
"title" : { type: String },
"user_id" : { type: String },
"blog_uri" :{ type: String },
"post_date" : { type : Date, default: Date.now},
"body" : { type: String, default: '' },
"comments" : [
{ 'content' : { type: String },
'user_id' : { type: String },
'comment_date' : { type: Date },
'votes' : [
{
'user_id' : { type: String }
}
]
}
],
"hidden" : {type:Boolean, default: false }
});
mongoose.model('Blog', BlogSchema);
So let's create a separate file called BlogController.js where we will write methods for CRUD.
var mongoose = require('mongoose');
var Blog = mongoose.model('Blog');
var ObjectId = require('mongoose').Types.ObjectId;
exports.create = function(req,res){
var blog = new Blog(req.body);
blog.save(function(err){
if(err)
res.json({message: "Error occured while saving"});
else{
res.redirect('/home');
}
});
};
exports.getAll = function(req,res){
Blog.find(function(err,blogs){
if(err){
res.send(err);
}else{
res.json(blogs);
}
});
};
exports.get = function(req,res){
var id ;
try{
id = new ObjectId(req.params.id);
Blog.findById(id,function(err,blog){
if(err){
res.send(err);
}else{
res.render('blog.ejs', {
blog: blog
});
}
});
}catch(e){
res.send(404);
}
};
exports.update = function(req,res){
var id ;
try{
id = new ObjectId(req.params.blog_id);
Blog.findById(id,function(err,blog){
if(err){
res.send(err);
}
blog.save(function(err){
if(err)
res.send(err);
res.render('blog.ejs', {
message: "Blog Updated successfully"
});
});
});
}catch(e){
res.send(404);
}
};
exports.delete = function(req,res){
var id ;
try{
id = new ObjectId(req.params.blog_id);
Blog.remove({_id:id},function(err,blog){
if(err){
res.send(err);
}
res.render('blog.ejs', {
message: "Blog deleted successfully"
});
});
}catch(e){
res.send(404);
}
};
So this was about CRUD using Mongoose. I usually don't use res.render(..) in my projects because i put Templating logic in front end. I just use res.json(..) and pass the json data to the the frontend. So please go ahead and try. I hope i answered your question. You can refer to
this repo, for better example. Here i got a very clean CRUD implementation.