I currently have a schema:
var User = new Schema({
id: String,
position: [{
_id:String,
title: String,
location: String,
start: String,
term:Number,
description:String,
date: {type: Date, default: Date.now},
applied:[{
candidate_id: String,
_id:String
}],
}]
I'm trying to insert data into the 'applied' subdocument but cant seem to get it working.
my function:
app.post('/apply',function (req,res){
//hard coded for testing purposes
User.update({id:mongoose.Types.ObjectId("58c2871414cd3d209abf5fc9"),"position._id":mongoose.Types.ObjectId("58d6b7e11e793c9a506ffe8f")},
{$push:{"position.$.applied":{
candidate_id:"test"
}
}
}).exec(function (err, result) {
console.log(result);
res.send({result:result});
});
});
For some reason this wont insert anything for me, the id's are definitely correct also. Anyone know where I'm going wrong?
Return after debug:
Database:
Related
I was wondering how I can update the array of likes with mongoose:
var postSchema = new mongoose.Schema({
author: String,
content: String,
date: String,
likes: [{theID: String}],
numDate: Number
});
var UserSchema = mongoose.Schema({
username: {
type: String
},
password: {
type: String
},
email: {
type: String
},
first: {
type: String
},
posts: [postSchema],
last: {
type: String
},
followers: [{theID: String}],
following: [{theID: String}],
img: { data: Buffer, contentType: String },
admin: {type: Boolean, default: false}
});
I can push things like new posts to a certain user in the database by
doing this:
User.update({_id: req.user.id}, {
$push: {"posts": {_id : req.body.theData}}
}, function(err, user){
res.redirect('profile');
});
Is there a similar way I can look at a specific user and then a specific post that the user has and update it to push a string to the likes array?
First Of all you need to select the post where you want to update like dislike, you can do it with the help of _id of post {_id: req.user.id,_id:posts._id} then you will need to update like array that can be done this way {$push: {"posts.$.likes": req.user.anotherUserId}} //anotherUserId is of user who liked it. same way you can take a pull of user id if user dislikes the post to remove id from array.
User.update({_id: req.user.id,_id:posts._id}, {
$push: {"posts.$.likes": req.user.id}
}, function(err, user){
});
can someone help me with a mongoose operation? I'm currently building this voting system.
I have this Poll model as:
var Poll = new Schema({
title: {
type: String,
required: true
},
options: [{text:String, count: {type: Number, default: 0}}],
author: {
type: Schema.ObjectId,
ref: 'Account',
},
disabled: {
type:Boolean,
default: false,
},
date: {type: Date, defalut: Date.now},
});
and I have this Log model as:
var Log = new Schema({
ip: String,
voter: {
type: Schema.ObjectId,
ref: 'Account'
},
poll: {
type: Schema.ObjectId,
ref: 'Poll'
},
date: {type: Date, defalut: Date.now},
});
each time a user vote for something , log will create something like:
{ ip: '::1',
voter: 5824e7c3b6e659459818004f,
poll: 58264b48f767f2270452b5cb,
_id: 58264b4cf767f2270452b5ce }
now should a user delete one of his poll, say 58264b48f767f2270452b5cb , I would like to also remove all the log documents that has same poll id in it.
I read some other answer and came up a middleware with
Poll.pre('remove', function(next){
var err = new Error('something went wrong');
this.model('Log').remove({poll: this._id}, function(err){
if (err) throw err;
})
next(err);
});
but it's not working at all.
what should I do? Thanks.
At the current state Model.remove() calls don't use hooks, why? Because a document could not be present in memory at time of the call, so would be necessary to query mongo first and then delete the doc to make sure a hook would work properly.
There's a CR for adding this behavior but is not implemented, yet.
So the current way to do this is to use something like:
myDoc.remove();
An example, this won't work:
var myAccount = new Account({
name: "jim"
})
var myPoll = new Poll({
question: "You like stuff?"
})
var myLog = new Log({
voter: myAccount,
poll: myPoll
})
myAccount.save()
.then(myPoll.save())
.then(myLog.save())
.then(Poll.remove({
question: "You like stuff?"
}, function(err) {
console.log(err)
}))
This will work instead:
myAccount.save()
.then(myPoll.save())
.then(myLog.save())
.then(myPoll.remove(function(err) {
console.log(err)
}))
Hello so I am making a basic app with users and posts.
I followed the mongoose documentation on population (http://mongoosejs.com/docs/2.7.x/docs/populate.html) and setup my Schemas so that the users and be connected to posts
var userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
email: String,
created_at: Date,
updated_at: Date,
admin: Boolean,
posts: [{ type: mongoose.Schema.ObjectId, ref: 'Post' }]
});
var postSchema = new mongoose.Schema({
_user : [{ type: mongoose.Schema.ObjectId, ref: 'User' }],
audioFile: { type: String, required: true },
imageFile: { type: String },
title: { type: String, required: true },
artist: { type: String, required: true },
start: { type: String, required: true },
stop: { type: String, required: true },
genre: { type: String, required: true },
tags: [{ type: String }]
});
app.get('/', function (req, res){
Post.find({}, function(err, allPosts){
if(!err){
res.render('main.njk', {
posts : allPosts,
title : 'Title',
isLogged : req.session.isLogged,
user : req.session.user,
messages : req.flash('alert')
});
} else { return done(err); }
});
});
Thats all fine and gravy and I can run a foreach loop on allPosts to pull each one in my HTML, but when I try to think of how I am going to display all the posts with their respective users attached to each post I am unsure of how to connect the two since all the examples in the mongoose doc is just mainly for findOne.
I was thinking something like this
app.get('/', function (req, res){
Post.find({}, function(err, allPosts){
if(!err){
allPosts.populate('_user', ['username']);
allPosts.exec(function (err, users){
if(err) console.log(err);
console.log(users);
});
res.render('main.njk', {
posts : allPosts,
title : 'Spaurk.net',
isLogged : req.session.isLogged,
user : req.session.user,
messages : req.flash('alert')
});
} else { return done(err); }
});
});
but that doesn't work of course.
So I was wondering if anyone with experience with this situation would be able to help me solve this.
Thanks a lot for any input.
EDIT, thanks to Daves help I was able to get the populate to work properly, I just cant pull the fields I want correctly with
Post.find({}).populate('_user').exec(function(err, allPosts){
In my loop {% for post in posts %}
, when I do post._user it shows the whole user schema, but when I do post._user.username it doesn't return anything. I am unsure as to why this is.
The proper way to structure a populate on a query is like this:
Post.find({})
.populate('_user')
.exec((err, allposts){...})
Then you will have an array of your Posts with the _user array populated. If you need to access a property of a user, you will need to do another loop through the _user array or specify with use you want to use _user[0].<property>
Here is my schema:
/** Schemas */
var profile = Schema({
EmailAddress: String,
FirstName: String,
LastName: String,
BusinessName: String
});
var convSchema = Schema({
name: String,
users: [{
type: Schema.Types.ObjectId,
ref: 'Profiles'
}],
conversationType: {
type: String,
enum: ['single', 'group'],
default: 'single'
},
created: {
type: Date,
default: Date.now
},
lastUpdated: {
type: Date,
default: Date.now
}
});
/** Models */
db.Profiles = mongoose.model('Profiles', profile);
db.Conversations = mongoose.model('ChatConversations', convSchema);
module.exports = db;
Then I try to populate Users using following code (http://mongoosejs.com/docs/populate.html):
db.Conversations.find(query).populate('users').exec(function (err, records) {
console.log(records);
});
This is returning records but users array as a blank array [].
I also tried the other way around (http://mongoosejs.com/docs/api.html#model_Model.populate):
db.Conversations.find(query, function (err, records) {
db.Conversations.populate(records, {path: "users", select: "BusinessName"}, function (err, records) {
console.log(records);
});
});
Results are same. When I checked references into profile collection records are there.
Any idea what wrong here?
I got it working by renaming model (the 3rd arguement):
mongoose.model( "Profiles", profile, "Profiles" );
The issue was Mongoose was searching for profiles collection but its there as Profiles in database. So I renamed it to Profiles to match the exact name.
Phewww! Thanks to me.
I have a model in mongoose that looks similar to this:
var TestSchema = new Schema({
test_username: {type: String, required: true},
test_content: {type: String},
reactions: [{
test_username: {type: String, required: true},
value: {type: Number, required: true},
sent_at: {type: Date, required: true, default: Date.now}
}],
created_at: {type: Date, default: Date.now},
updated_at: {type: Date, default: Date.now}
})
it stores my Test object with many reactions in it. Each reaction contains either 1 or -1 value and different usernames.
Now I'm trying to create an endpoint that gets the Test id as an input and returns the total, summed amount from all reactions that it contains.
I started writing it as:
testRoutes.get('/:id/reactions/', functions.validateRequestsGET, function(req, res){
var testId = req.params.id;
var query = Test... //here I'm stuck
query.exec(function(err, reactions){
if(err) {
res.send(err);
return;
}
res.json(reactions);
});
});
can you give me a hint of how to create a query that could return me a json with the summed amount? something like {reactions: 17} or similar?
Try this:
Test.aggregate(
{ $match: {
_id: testId // you might want to convert this from string to ObjectId()
}},
{ $project: {
sumReactions: { $sum: "$reactions.value" }
}}
)
Take a look at group accumulators $group in documentation , good examples too.