why isnt findbyidandupdate pushing new comment into array? - node.js

I'm trying to add in comments in an array to a main comment. Here i'm getting getting data, using it to create a new comment, and then pushing it into it's parent comment in the children array. But when it findbyidandupdate goes through, the parent comment doesn't have this comment in its children array.
I did a second find below it to see if it returns new updated children array but nothing. I'm inputting the new comment's id into the children array.
my schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PK = mongoose.Types.ObjectId;
var RK = mongoose.Schema.ObjectId;
var CommentSchema = Schema({
body: {type: String},
chapterId: {type: RK, ref: 'Chapter'},
by: {type: RK, ref: 'User'},
children: [{
type: RK,
ref: 'Comment'
}]
}, {timestamps: true});
function autoPopulateComment() {
this.populate('by');
}
CommentSchema.
pre('findOne', autoPopulateComment).
pre('find', autoPopulateComment);
module.exports = mongoose.model('Comment', CommentSchema)
;
my controller:
commentController.reply = function(req,res){
var commentList;
var newComment = new Comment(req.body);
newComment.save();
console.log(newComment);
var commid = req.body.comid;
//console.log(req.body.comid);
//console.log(req.body.body);
//console.log(req.body.xxchid);
//console.log(req.body.by);
Comment.findByIdAndUpdate(
commid,
{$push: {"children": newComment._id}},
{new: true}
)
Comment.find({_id: commid}).then(function(comment){
console.log(comment);
})
Chapter.find({_id: req.xxchid}).then(function(chapter){
Comment.find({chapterId: req.xxchid}).then(function(data){
return res.send({commentList: data, comidd: commid, test1:"testy"})
})
})
}

Changed the update function to this and it worked. Guess it needed a callback shrugs. Anyways thnx stackoverflow! hehexd
Comment.findByIdAndUpdate(
commid,
{$push: {children: newComment}},
{new: true},
function(err, post){
if(err){
console.log(err);
} else{
console.log(post+"haha")
}
}
)

Related

How to add an objectID to recursively embedded subdocuments

I have a variation on the question asked and solved by #Guilherme here but my recursive embedded documents are within another schema like this;
var mongoose = require('mongoose');
var CollectPointSchema = new mongoose.Schema({
name: {type: String},
collectPoints: [ this ]
});
var GroupSchema = new mongoose.Schema({
label: {type: String},
points: [CollectionPointSchema]
});
const Group = mongoose.model("Group", GroupSchema);
I'd like to modify the solution that Guilherme proposed here but not sure how to go about it.
The main problem was that the child folders were not being populated with the name: field. I think because that field is not in the top level of the schema. So as a work-around I have added the name: field to the parent schema like this;
var GroupSchema = new mongoose.Schema({
label: {type: String},
name: {type: String},
points: [CollectionPointSchema]
});
and I also needed to change the order of Guilherme's solution from this;
var FolderModel = mongoose.model('folders', FolderSchema);
FolderSchema.pre('save', function(next) {
if (this.isNew) {
recursive_reference(FolderModel, this, "folders")
}
next();
});
to this;
FolderSchema.pre('save', function(next) {
if (this.isNew) {
recursive_reference(FolderModel, this, "folders")
}
next();
});
var FolderModel = mongoose.model('folders', FolderSchema);
The result is that I have an unused field at the parent level, but it works.

"Item" schema is not found even i required that model.(mongoose,Node.js)

I am trying to run hook of 'remove' in label schema."Item.find is not a function" this is the error which I got.
But 'Item' schema is not found.This "require" works fine on other models.Here it is not working.
That error might be occurs in var Item = require('./Item');
This is "Label" schema.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Item = require('./Item');
var List = require('./List');
// created schema for Item
var labelSchema = new Schema({
label_title: {type: String},
color_id:{type: String, required: true},
created_at: Date,
updated_at: Date,
marked : { Boolean ,default:false },
_board: {type: Schema.Types.ObjectId, ref:'Board'}
});
//-----------------Hook--
labelSchema.post('remove',function(doc,next){
Label.remove({_id:this._id}).then(function(data){
console.log("successfuly removed label");
}).catch(function(error){console.log(error);
})
//-----remove label from all items
// console.log("ITEM", Item);
Item.find({},function(error,items){
items.forEach(function(item){
Item.findByIdAndUpdate(item._id,
{ "$pullAll": { "label" : [{ "label_id" : this._id }]} },function(error,result){
if(result)console.log("successfully removed");
else console.log("not removed");
})
})
})
});
var Label = mongoose.model('Label', labelSchema);
module.exports = Label;
What should I do?

Mongoose remove document with references

I have two Schemas, eventSchema and personSchema as shown below:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var eventSchema = Schema({
title : String,
location : String,
startDate : Date,
endDate : Date
});
var personSchema = Schema({
firstname: String,
lastname: String,
email: String,
dob: Date,
city: String,
eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});
var Event = mongoose.model('Event', eventSchema);
var Person = mongoose.model('Person', personSchema);
How can I remove all eventsAttended from a deleted Person?
For example, if I remove a Person then I expect that all events assigned to that Person will be removed.
This is my code:
Person.findOneAndRemove({_id: req.body._id}, (err, response) => {
// remove the events assigned to this person
})
With mongoose you can use pre and post middleware on your schemas:
personSchema.post('remove', removeLinkedDocuments);
Then in the removeLinkedDocuments callback, you can remove all linked documents:
function removeLinkedDocuments(doc) {
// doc will be the removed Person document
Event.remove({_id: { $in: doc.eventsAttended }})
}
Note the middleware is only called for the following methods (refer to the linked documentation for details):
count
find
findOne
findOneAndRemove
findOneAndUpdate
update
To remove the documents 'manually' in your callback, you might do
Person.findOneAndRemove({_id: req.body._id}, (err, response) => {
// note that if you have populated the Event documents to
// the person documents, you have to extract the id from the
// req.body.eventsAttended object
Event.remove({_id: { $in: req.body.eventsAttended }}, (err, res) => {
...
})
})

How to populate a mongoose schema

I have the following mongoose schemas
var postTable = mongoose.Schema({
userPost:{type : String},
dateCreated: {type: Date, default: Date.now},
_replies:[{type: mongoose.Schema.Types.ObjectId, ref: 'reply_table'}],
_creator:{type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});
and
var reply_table = mongoose.Schema({
userReply:{type:String},
date_created:{type:Date, default: Date.now},
_post:{type: mongoose.Schema.Types.ObjectId, ref: 'post'},
_creator:{type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});
var userPost = module.exports = mongoose.model("Post",postTable);
var userReply = module.exports = mongoose.model('reply_table',reply_table);
User can create post which will be entered into the Post table and other users can comment or reply to a post which will be entered into the reply_table.
I then try to populate the the post table like this
module.exports.getPost = function (callback) {
var mysort = { dateCreated: -1 };
userPost
.find({},callback)
.sort(mysort)
.populate('_creator','username')
.populate(' _replies')
.exec(function (err,post) {
if(err) throw err;
console.log(post)
});
};
When the console prints out the post it prints the post information and a object with the user information becausei have another schema setup for users, therefore I used .populate('_creator','username')
The problem is it wont print the reply information it only prints an empty array: reply[].
I'm pretty sure I'm doing everything right. I used the following code to insert information into the reply_table
//make a reply on a post
module.exports.make_reply = function (user_id,pid,reply,callback) {
var newReply = userReply({
_creator: user_id,
_post: pid,
userReply: reply
});
newReply.save(callback);
}
I know this question is very long but does anyone have any idea of what I might be doing wrong. I only want to populate the Post schema with information from the reply_table
I finally figured out a solution to my question. What i did was i created a function to insert the reply id into the post table. It basically get the comment by its id and push a reply into the _replies array in the post table.
//Insert reply into post table
module.exports.addReply = function (id,reply) {
userPost.update({_id:id},{$push:{replies:reply}},{multi:true},function
(err,post) {
});
}
When i use the getPost function it populates the reply table
module.exports.getPost = function (callback) {
var mysort = {dateCreated: -1};
userPost
.find({}, callback)
.sort(mysort)
.populate('_creator', 'username')
.populate('replies')
.exec(function (err) {
if(err) throw err;
});
};

Use populate() for two different schemas in MongoDB

I have two MongoDB collections - comments
var mongoose = require('mongoose');
var CommentSchema = new mongoose.Schema({
body: String,
author: String,
upvotes: {type: Number, default: 0},
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Profile' }
});
mongoose.model('Comment', CommentSchema);
and users
var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
userName: String,
userJobRole: String,
userEmail: String,
userPhone: String,
userTimeZone: String,
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Profile' }
});
mongoose.model('User', UserSchema);
I want to use populate for each of these schemas in my get request. One for users and one for comments from these models.
router.get('/profiles/:profile', function(req, res, next) {
req.post.populate('users', function(err, post) {
if(err) { return next(err) }
res.json(post);
});
});
I can only figure out how to call one.
Does Mongoose allow you to populate from two schemas?
In order to populate multiple paths, you can pass a space delimited string of path names to the populate method on any document as follows:
Story
.find(...)
.populate('fans _creator') // space delimited path names
.exec()
This is taken directly from the Mongoose docs http://mongoosejs.com/docs/populate.html

Resources