So I have this Mongoose Schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
body: {type: String, required: true, max: 2000},
created: { type: Date, default: Date.now },
flags: {type: Number, default: 0},
lastFlag: {type: Date, default: Date.now()},
imageBanned: {type: Boolean, default: false},
fileName: {type: String, default: ""}
}, {
writeConcern: {
w: 0,
j: false,
wtimeout: 200
}
});
var PostSchema = new Schema({
body: {type: String, required: true, max: 2000},
created: { type: Date, default: Date.now },
flags: {type: Number, default: 0},
lastFlag: {type: Date, default: Date.now()},
fileName: {type: String, default: ""},
imageBanned: {type: Boolean, default: false},
board: {type: String, default: ""},
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
}, {
writeConcern: {
w: 0,
j: false,
wtimeout: 200
}
});
var Post = mongoose.model('Post', PostSchema);
var Comment = mongoose.model('Comment', CommentSchema)
module.exports = {Post, Comment}
And I'm trying to query a Comment inside the comment array in post.
This is the endpoint I'm trying:
router.post('/flagComment', (req, res, next)=>{
console.log('inside /flagComment')
console.log('value of req.body: ', req.body)
model.Post.findOne({"comments._id": req.body.id}).exec((err, doc)=>{
if(err){
console.log('there was an error: ', err)
}
console.log('the value of the found doc: ', doc)
res.json({dummy: 'dummy'})
})
})
However, this gives the following terminal output:
value of req.body: { id: '5c9bd902bda8d371d5c808dc' }
the value of the found doc: null
That's not correct...I've verified the ID is correct - why is the comment doc not being found?
EDIT:
I've attempted this solution (Can't find documents searching by ObjectId using Mongoose) by setting the objectID like this:
var ObjectId = require('mongoose').Types.ObjectId;
router.post('/flagComment', (req, res, next)=>{
console.log('inside /flagComment')
console.log('value of req.body: ', req.body)
console.log('value of objid req id : ', ObjectId(req.body.id))
model.Post.find({"comments._id": ObjectId(req.body.id)}).exec((err, doc)=>{
if(err){
console.log('there was an error: ', err)
}
console.log('the value of the found doc: ', doc)
res.json({dummy: 'dummy'})
})
})
And I get the following terminal output:
value of req.body: { id: '5c9bd902bda8d371d5c808dc' }
value of objid req id : 5c9bd902bda8d371d5c808dc
the value of the found doc: []
So, this is not yet a solution although it appears to be better than what I had.