Mongodb Can't Query SubDocument by ID (returns null)Can't find documents searching by ObjectId using MongooseMongoose String to ObjectIDMongoose Saved _id'ss as a string instead of ObjectIdMongoose sometimes save objectId as string, some times noHow to check empty/undefined/null string in JavaScript?How can I get query string values in JavaScript?event.preventDefault() vs. return falseHow to determine if variable is 'undefined' or 'null'?MongoDB vs. CassandraHow to query MongoDB with “like”?Is there a standard function to check for null, undefined, or blank variables in JavaScript?Why does ++[[]][+[]]+[+[]] return the string “10”?How do I return the response from an asynchronous call?I got an empty array in sub document array saving using mongoose ( MEAN stack)
Can I create something like a macro in Numbers?
Can I use coax outlets for cable modem?
Why is explainability not one of the criteria for publication?
Why this brute force attack doesn't reduce all cryptographic hash functions' security bits against collision attacks to N/3?
How do solar inverter systems easily add AC power sources together?
Is a memoized pure function itself considered pure?
Did ancient peoples ever hide their treasure behind puzzles?
Why is there not a willingness from the world to step in between Pakistan and India?
Force SQL Server to use fragmented indexes?
Shift lens vs move body?
Group riding etiquette
How many petaflops does it take to land on the moon? What does Artemis need with an Aitken?
Why can't you say don't instead of won't?
Alternatives to Network Backup
Talk interpreter
How to pass 2>/dev/null as a variable?
Is it true that different variants of the same model aircraft don't require pilot retraining?
Could the UK amend the European Withdrawal Act and revoke the Article 50 invocation?
Is there an in-universe explanation given to the senior Imperial Navy Officers as to why Darth Vader serves Emperor Palpatine?
What is Soda Fountain Etiquette?
Can I lend at the federal funds rate?
Is it unusual for a math department not to have a mail/web server?
Notice period 60 days but I need to join in 45 days
What is the sound/audio equivalent of "unsightly"?
Mongodb Can't Query SubDocument by ID (returns null)
Can't find documents searching by ObjectId using MongooseMongoose String to ObjectIDMongoose Saved _id'ss as a string instead of ObjectIdMongoose sometimes save objectId as string, some times noHow to check empty/undefined/null string in JavaScript?How can I get query string values in JavaScript?event.preventDefault() vs. return falseHow to determine if variable is 'undefined' or 'null'?MongoDB vs. CassandraHow to query MongoDB with “like”?Is there a standard function to check for null, undefined, or blank variables in JavaScript?Why does ++[[]][+[]]+[+[]] return the string “10”?How do I return the response from an asynchronous call?I got an empty array in sub document array saving using mongoose ( MEAN stack)
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
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.
javascript node.js database mongodb mongoose
add a comment |
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.
javascript node.js database mongodb mongoose
Possible duplicate of Mongoose String to ObjectID
– amcgregor
Mar 28 at 17:11
…or Mongoose saved _id's as string instead of ObjectId or Mongoose sometimes save ObjectId as string… — while these relate to the data storage side of the problem, every single one features the solution.
– amcgregor
Mar 28 at 17:22
add a comment |
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.
javascript node.js database mongodb mongoose
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.
javascript node.js database mongodb mongoose
javascript node.js database mongodb mongoose
edited Mar 27 at 20:52
Peter Weyand
asked Mar 27 at 20:36
Peter WeyandPeter Weyand
5079 silver badges41 bronze badges
5079 silver badges41 bronze badges
Possible duplicate of Mongoose String to ObjectID
– amcgregor
Mar 28 at 17:11
…or Mongoose saved _id's as string instead of ObjectId or Mongoose sometimes save ObjectId as string… — while these relate to the data storage side of the problem, every single one features the solution.
– amcgregor
Mar 28 at 17:22
add a comment |
Possible duplicate of Mongoose String to ObjectID
– amcgregor
Mar 28 at 17:11
…or Mongoose saved _id's as string instead of ObjectId or Mongoose sometimes save ObjectId as string… — while these relate to the data storage side of the problem, every single one features the solution.
– amcgregor
Mar 28 at 17:22
Possible duplicate of Mongoose String to ObjectID
– amcgregor
Mar 28 at 17:11
Possible duplicate of Mongoose String to ObjectID
– amcgregor
Mar 28 at 17:11
…or Mongoose saved _id's as string instead of ObjectId or Mongoose sometimes save ObjectId as string… — while these relate to the data storage side of the problem, every single one features the solution.
– amcgregor
Mar 28 at 17:22
…or Mongoose saved _id's as string instead of ObjectId or Mongoose sometimes save ObjectId as string… — while these relate to the data storage side of the problem, every single one features the solution.
– amcgregor
Mar 28 at 17:22
add a comment |
2 Answers
2
active
oldest
votes
You aren't querying for an ObjectId, no matter how much you think you are. You are querying for the ObjectId encoded as a hexidecial string, which is not the same thing. Properly typecast and you will likely have far more success.
Edited to elaborate, from a mongo (JS) REPL shell:
> // Omitting the _id, or generating a new one, are equivalent during insert.
> db.foo.insert(_id: ObjectId())
WriteResult( "nInserted" : 1 )
> db.foo.find() // As expected, we get back our _real_ ObjectId value.
"_id" : ObjectId("5c9cfab873724727778c0730")
> // Can we "insert the record again" using a string version of the ID?
> db.foo.insert(_id: "5c9cfab873724727778c0730")
WriteResult( "nInserted" : 1 ) // Sure as heck can! No unique violation!
> db.foo.find() // Because THESE ARE NOT THE SAME
"_id" : ObjectId("5c9cfab873724727778c0730")
"_id" : "5c9cfab873724727778c0730"
After our IRC discussion, there seems to be difficulty in understanding the "searchable terms" in the answers you are being given. Search here on StackOverflow (or Google, or DDG) for "mongoose typecast ObjectId" (without quotes; or just "mongoose ObjectId"…) and you will find many answers, as this is a particularly common problem for Mongoose users.
Can you provide a code example? I'm not sure I understand.
– Peter Weyand
Mar 27 at 20:44
@PeterWeyand I do not Mongoose, and I do not JS. The answer is clear: typecast the value to a realObjectId
before attempting to query using the value. A hex-encoded string != the binary value, the same as a base64-encoded string != the original binary value.
– amcgregor
Mar 27 at 20:45
Alright, well thanks for your help, but this answer is not yet enough to get me to a solution. Thank you.
– Peter Weyand
Mar 27 at 20:47
@PeterWeyand For giggles, I did update with some code from amongo
REPL shell, which is JS. This code demonstrates the exact problem you are encountering from the perspective of using the unique index on_id
to prove dissimilarity and inability/inappropriateness of comparison. The answer given ("properly typecast") stands.
– amcgregor
Mar 28 at 16:59
add a comment |
Once try checking with populating the reference data first and then querying on the _id of the comment.
*Get the post id also from front end in addition to comment id, in that way it will be easier.
Post.findOne(_id:'postId')
.populate(
path : 'comment',
match : _id : 'commentId'
)
.exec(...);
Thanks...I mean this works, but...it feels like a backdoor hack a little bit. Why can't I just query the comment by id directly? I think doing it this way requires A) obv. passing another id and B) I think searching Post when I don't have to which is another query.
– Peter Weyand
Mar 27 at 21:14
if you check the database, mongodb doesn't save the data in comment field like you are searching "comments._id", It save in the format something like "$ref" : "comment", "$id" : ObjectId("commentid"), "$db" : "dbname"
– user1361425
Mar 27 at 21:16
I don't believe that is correct. Here is the terminal output of a post:flags: 0, lastFlag: 2019-03-27T21:00:54.316Z, fileName: '1553720454192&&hotdog.png', imageBanned: false, board: 'nsfw', comments: [ flags: 0, lastFlag: 2019-03-27T21:01:03.540Z, imageBanned: false, fileName: '1553720463408&&hotdog.png', _id: 5c9be48f0556ec5397cb62a2, body: 'dadf', created: 2019-03-27T21:01:03.540Z, __v: 0 ], _id: 5c9be4860556ec5397cb62a1, body: 'dog', created: 2019-03-27T21:11:15.575Z, __v: 0
– Peter Weyand
Mar 27 at 21:21
If your question has been answered, please make sure to accept answer for further references.
– user1361425
Mar 27 at 21:28
It has not yet been answered - please refer to my comments, thank you.
– Peter Weyand
Mar 27 at 21:29
|
show 4 more comments
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55386030%2fmongodb-cant-query-subdocument-by-id-returns-null%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You aren't querying for an ObjectId, no matter how much you think you are. You are querying for the ObjectId encoded as a hexidecial string, which is not the same thing. Properly typecast and you will likely have far more success.
Edited to elaborate, from a mongo (JS) REPL shell:
> // Omitting the _id, or generating a new one, are equivalent during insert.
> db.foo.insert(_id: ObjectId())
WriteResult( "nInserted" : 1 )
> db.foo.find() // As expected, we get back our _real_ ObjectId value.
"_id" : ObjectId("5c9cfab873724727778c0730")
> // Can we "insert the record again" using a string version of the ID?
> db.foo.insert(_id: "5c9cfab873724727778c0730")
WriteResult( "nInserted" : 1 ) // Sure as heck can! No unique violation!
> db.foo.find() // Because THESE ARE NOT THE SAME
"_id" : ObjectId("5c9cfab873724727778c0730")
"_id" : "5c9cfab873724727778c0730"
After our IRC discussion, there seems to be difficulty in understanding the "searchable terms" in the answers you are being given. Search here on StackOverflow (or Google, or DDG) for "mongoose typecast ObjectId" (without quotes; or just "mongoose ObjectId"…) and you will find many answers, as this is a particularly common problem for Mongoose users.
Can you provide a code example? I'm not sure I understand.
– Peter Weyand
Mar 27 at 20:44
@PeterWeyand I do not Mongoose, and I do not JS. The answer is clear: typecast the value to a realObjectId
before attempting to query using the value. A hex-encoded string != the binary value, the same as a base64-encoded string != the original binary value.
– amcgregor
Mar 27 at 20:45
Alright, well thanks for your help, but this answer is not yet enough to get me to a solution. Thank you.
– Peter Weyand
Mar 27 at 20:47
@PeterWeyand For giggles, I did update with some code from amongo
REPL shell, which is JS. This code demonstrates the exact problem you are encountering from the perspective of using the unique index on_id
to prove dissimilarity and inability/inappropriateness of comparison. The answer given ("properly typecast") stands.
– amcgregor
Mar 28 at 16:59
add a comment |
You aren't querying for an ObjectId, no matter how much you think you are. You are querying for the ObjectId encoded as a hexidecial string, which is not the same thing. Properly typecast and you will likely have far more success.
Edited to elaborate, from a mongo (JS) REPL shell:
> // Omitting the _id, or generating a new one, are equivalent during insert.
> db.foo.insert(_id: ObjectId())
WriteResult( "nInserted" : 1 )
> db.foo.find() // As expected, we get back our _real_ ObjectId value.
"_id" : ObjectId("5c9cfab873724727778c0730")
> // Can we "insert the record again" using a string version of the ID?
> db.foo.insert(_id: "5c9cfab873724727778c0730")
WriteResult( "nInserted" : 1 ) // Sure as heck can! No unique violation!
> db.foo.find() // Because THESE ARE NOT THE SAME
"_id" : ObjectId("5c9cfab873724727778c0730")
"_id" : "5c9cfab873724727778c0730"
After our IRC discussion, there seems to be difficulty in understanding the "searchable terms" in the answers you are being given. Search here on StackOverflow (or Google, or DDG) for "mongoose typecast ObjectId" (without quotes; or just "mongoose ObjectId"…) and you will find many answers, as this is a particularly common problem for Mongoose users.
Can you provide a code example? I'm not sure I understand.
– Peter Weyand
Mar 27 at 20:44
@PeterWeyand I do not Mongoose, and I do not JS. The answer is clear: typecast the value to a realObjectId
before attempting to query using the value. A hex-encoded string != the binary value, the same as a base64-encoded string != the original binary value.
– amcgregor
Mar 27 at 20:45
Alright, well thanks for your help, but this answer is not yet enough to get me to a solution. Thank you.
– Peter Weyand
Mar 27 at 20:47
@PeterWeyand For giggles, I did update with some code from amongo
REPL shell, which is JS. This code demonstrates the exact problem you are encountering from the perspective of using the unique index on_id
to prove dissimilarity and inability/inappropriateness of comparison. The answer given ("properly typecast") stands.
– amcgregor
Mar 28 at 16:59
add a comment |
You aren't querying for an ObjectId, no matter how much you think you are. You are querying for the ObjectId encoded as a hexidecial string, which is not the same thing. Properly typecast and you will likely have far more success.
Edited to elaborate, from a mongo (JS) REPL shell:
> // Omitting the _id, or generating a new one, are equivalent during insert.
> db.foo.insert(_id: ObjectId())
WriteResult( "nInserted" : 1 )
> db.foo.find() // As expected, we get back our _real_ ObjectId value.
"_id" : ObjectId("5c9cfab873724727778c0730")
> // Can we "insert the record again" using a string version of the ID?
> db.foo.insert(_id: "5c9cfab873724727778c0730")
WriteResult( "nInserted" : 1 ) // Sure as heck can! No unique violation!
> db.foo.find() // Because THESE ARE NOT THE SAME
"_id" : ObjectId("5c9cfab873724727778c0730")
"_id" : "5c9cfab873724727778c0730"
After our IRC discussion, there seems to be difficulty in understanding the "searchable terms" in the answers you are being given. Search here on StackOverflow (or Google, or DDG) for "mongoose typecast ObjectId" (without quotes; or just "mongoose ObjectId"…) and you will find many answers, as this is a particularly common problem for Mongoose users.
You aren't querying for an ObjectId, no matter how much you think you are. You are querying for the ObjectId encoded as a hexidecial string, which is not the same thing. Properly typecast and you will likely have far more success.
Edited to elaborate, from a mongo (JS) REPL shell:
> // Omitting the _id, or generating a new one, are equivalent during insert.
> db.foo.insert(_id: ObjectId())
WriteResult( "nInserted" : 1 )
> db.foo.find() // As expected, we get back our _real_ ObjectId value.
"_id" : ObjectId("5c9cfab873724727778c0730")
> // Can we "insert the record again" using a string version of the ID?
> db.foo.insert(_id: "5c9cfab873724727778c0730")
WriteResult( "nInserted" : 1 ) // Sure as heck can! No unique violation!
> db.foo.find() // Because THESE ARE NOT THE SAME
"_id" : ObjectId("5c9cfab873724727778c0730")
"_id" : "5c9cfab873724727778c0730"
After our IRC discussion, there seems to be difficulty in understanding the "searchable terms" in the answers you are being given. Search here on StackOverflow (or Google, or DDG) for "mongoose typecast ObjectId" (without quotes; or just "mongoose ObjectId"…) and you will find many answers, as this is a particularly common problem for Mongoose users.
edited Mar 28 at 17:14
answered Mar 27 at 20:43
amcgregoramcgregor
7677 silver badges23 bronze badges
7677 silver badges23 bronze badges
Can you provide a code example? I'm not sure I understand.
– Peter Weyand
Mar 27 at 20:44
@PeterWeyand I do not Mongoose, and I do not JS. The answer is clear: typecast the value to a realObjectId
before attempting to query using the value. A hex-encoded string != the binary value, the same as a base64-encoded string != the original binary value.
– amcgregor
Mar 27 at 20:45
Alright, well thanks for your help, but this answer is not yet enough to get me to a solution. Thank you.
– Peter Weyand
Mar 27 at 20:47
@PeterWeyand For giggles, I did update with some code from amongo
REPL shell, which is JS. This code demonstrates the exact problem you are encountering from the perspective of using the unique index on_id
to prove dissimilarity and inability/inappropriateness of comparison. The answer given ("properly typecast") stands.
– amcgregor
Mar 28 at 16:59
add a comment |
Can you provide a code example? I'm not sure I understand.
– Peter Weyand
Mar 27 at 20:44
@PeterWeyand I do not Mongoose, and I do not JS. The answer is clear: typecast the value to a realObjectId
before attempting to query using the value. A hex-encoded string != the binary value, the same as a base64-encoded string != the original binary value.
– amcgregor
Mar 27 at 20:45
Alright, well thanks for your help, but this answer is not yet enough to get me to a solution. Thank you.
– Peter Weyand
Mar 27 at 20:47
@PeterWeyand For giggles, I did update with some code from amongo
REPL shell, which is JS. This code demonstrates the exact problem you are encountering from the perspective of using the unique index on_id
to prove dissimilarity and inability/inappropriateness of comparison. The answer given ("properly typecast") stands.
– amcgregor
Mar 28 at 16:59
Can you provide a code example? I'm not sure I understand.
– Peter Weyand
Mar 27 at 20:44
Can you provide a code example? I'm not sure I understand.
– Peter Weyand
Mar 27 at 20:44
@PeterWeyand I do not Mongoose, and I do not JS. The answer is clear: typecast the value to a real
ObjectId
before attempting to query using the value. A hex-encoded string != the binary value, the same as a base64-encoded string != the original binary value.– amcgregor
Mar 27 at 20:45
@PeterWeyand I do not Mongoose, and I do not JS. The answer is clear: typecast the value to a real
ObjectId
before attempting to query using the value. A hex-encoded string != the binary value, the same as a base64-encoded string != the original binary value.– amcgregor
Mar 27 at 20:45
Alright, well thanks for your help, but this answer is not yet enough to get me to a solution. Thank you.
– Peter Weyand
Mar 27 at 20:47
Alright, well thanks for your help, but this answer is not yet enough to get me to a solution. Thank you.
– Peter Weyand
Mar 27 at 20:47
@PeterWeyand For giggles, I did update with some code from a
mongo
REPL shell, which is JS. This code demonstrates the exact problem you are encountering from the perspective of using the unique index on _id
to prove dissimilarity and inability/inappropriateness of comparison. The answer given ("properly typecast") stands.– amcgregor
Mar 28 at 16:59
@PeterWeyand For giggles, I did update with some code from a
mongo
REPL shell, which is JS. This code demonstrates the exact problem you are encountering from the perspective of using the unique index on _id
to prove dissimilarity and inability/inappropriateness of comparison. The answer given ("properly typecast") stands.– amcgregor
Mar 28 at 16:59
add a comment |
Once try checking with populating the reference data first and then querying on the _id of the comment.
*Get the post id also from front end in addition to comment id, in that way it will be easier.
Post.findOne(_id:'postId')
.populate(
path : 'comment',
match : _id : 'commentId'
)
.exec(...);
Thanks...I mean this works, but...it feels like a backdoor hack a little bit. Why can't I just query the comment by id directly? I think doing it this way requires A) obv. passing another id and B) I think searching Post when I don't have to which is another query.
– Peter Weyand
Mar 27 at 21:14
if you check the database, mongodb doesn't save the data in comment field like you are searching "comments._id", It save in the format something like "$ref" : "comment", "$id" : ObjectId("commentid"), "$db" : "dbname"
– user1361425
Mar 27 at 21:16
I don't believe that is correct. Here is the terminal output of a post:flags: 0, lastFlag: 2019-03-27T21:00:54.316Z, fileName: '1553720454192&&hotdog.png', imageBanned: false, board: 'nsfw', comments: [ flags: 0, lastFlag: 2019-03-27T21:01:03.540Z, imageBanned: false, fileName: '1553720463408&&hotdog.png', _id: 5c9be48f0556ec5397cb62a2, body: 'dadf', created: 2019-03-27T21:01:03.540Z, __v: 0 ], _id: 5c9be4860556ec5397cb62a1, body: 'dog', created: 2019-03-27T21:11:15.575Z, __v: 0
– Peter Weyand
Mar 27 at 21:21
If your question has been answered, please make sure to accept answer for further references.
– user1361425
Mar 27 at 21:28
It has not yet been answered - please refer to my comments, thank you.
– Peter Weyand
Mar 27 at 21:29
|
show 4 more comments
Once try checking with populating the reference data first and then querying on the _id of the comment.
*Get the post id also from front end in addition to comment id, in that way it will be easier.
Post.findOne(_id:'postId')
.populate(
path : 'comment',
match : _id : 'commentId'
)
.exec(...);
Thanks...I mean this works, but...it feels like a backdoor hack a little bit. Why can't I just query the comment by id directly? I think doing it this way requires A) obv. passing another id and B) I think searching Post when I don't have to which is another query.
– Peter Weyand
Mar 27 at 21:14
if you check the database, mongodb doesn't save the data in comment field like you are searching "comments._id", It save in the format something like "$ref" : "comment", "$id" : ObjectId("commentid"), "$db" : "dbname"
– user1361425
Mar 27 at 21:16
I don't believe that is correct. Here is the terminal output of a post:flags: 0, lastFlag: 2019-03-27T21:00:54.316Z, fileName: '1553720454192&&hotdog.png', imageBanned: false, board: 'nsfw', comments: [ flags: 0, lastFlag: 2019-03-27T21:01:03.540Z, imageBanned: false, fileName: '1553720463408&&hotdog.png', _id: 5c9be48f0556ec5397cb62a2, body: 'dadf', created: 2019-03-27T21:01:03.540Z, __v: 0 ], _id: 5c9be4860556ec5397cb62a1, body: 'dog', created: 2019-03-27T21:11:15.575Z, __v: 0
– Peter Weyand
Mar 27 at 21:21
If your question has been answered, please make sure to accept answer for further references.
– user1361425
Mar 27 at 21:28
It has not yet been answered - please refer to my comments, thank you.
– Peter Weyand
Mar 27 at 21:29
|
show 4 more comments
Once try checking with populating the reference data first and then querying on the _id of the comment.
*Get the post id also from front end in addition to comment id, in that way it will be easier.
Post.findOne(_id:'postId')
.populate(
path : 'comment',
match : _id : 'commentId'
)
.exec(...);
Once try checking with populating the reference data first and then querying on the _id of the comment.
*Get the post id also from front end in addition to comment id, in that way it will be easier.
Post.findOne(_id:'postId')
.populate(
path : 'comment',
match : _id : 'commentId'
)
.exec(...);
edited Mar 27 at 21:05
answered Mar 27 at 20:59
user1361425user1361425
471 silver badge7 bronze badges
471 silver badge7 bronze badges
Thanks...I mean this works, but...it feels like a backdoor hack a little bit. Why can't I just query the comment by id directly? I think doing it this way requires A) obv. passing another id and B) I think searching Post when I don't have to which is another query.
– Peter Weyand
Mar 27 at 21:14
if you check the database, mongodb doesn't save the data in comment field like you are searching "comments._id", It save in the format something like "$ref" : "comment", "$id" : ObjectId("commentid"), "$db" : "dbname"
– user1361425
Mar 27 at 21:16
I don't believe that is correct. Here is the terminal output of a post:flags: 0, lastFlag: 2019-03-27T21:00:54.316Z, fileName: '1553720454192&&hotdog.png', imageBanned: false, board: 'nsfw', comments: [ flags: 0, lastFlag: 2019-03-27T21:01:03.540Z, imageBanned: false, fileName: '1553720463408&&hotdog.png', _id: 5c9be48f0556ec5397cb62a2, body: 'dadf', created: 2019-03-27T21:01:03.540Z, __v: 0 ], _id: 5c9be4860556ec5397cb62a1, body: 'dog', created: 2019-03-27T21:11:15.575Z, __v: 0
– Peter Weyand
Mar 27 at 21:21
If your question has been answered, please make sure to accept answer for further references.
– user1361425
Mar 27 at 21:28
It has not yet been answered - please refer to my comments, thank you.
– Peter Weyand
Mar 27 at 21:29
|
show 4 more comments
Thanks...I mean this works, but...it feels like a backdoor hack a little bit. Why can't I just query the comment by id directly? I think doing it this way requires A) obv. passing another id and B) I think searching Post when I don't have to which is another query.
– Peter Weyand
Mar 27 at 21:14
if you check the database, mongodb doesn't save the data in comment field like you are searching "comments._id", It save in the format something like "$ref" : "comment", "$id" : ObjectId("commentid"), "$db" : "dbname"
– user1361425
Mar 27 at 21:16
I don't believe that is correct. Here is the terminal output of a post:flags: 0, lastFlag: 2019-03-27T21:00:54.316Z, fileName: '1553720454192&&hotdog.png', imageBanned: false, board: 'nsfw', comments: [ flags: 0, lastFlag: 2019-03-27T21:01:03.540Z, imageBanned: false, fileName: '1553720463408&&hotdog.png', _id: 5c9be48f0556ec5397cb62a2, body: 'dadf', created: 2019-03-27T21:01:03.540Z, __v: 0 ], _id: 5c9be4860556ec5397cb62a1, body: 'dog', created: 2019-03-27T21:11:15.575Z, __v: 0
– Peter Weyand
Mar 27 at 21:21
If your question has been answered, please make sure to accept answer for further references.
– user1361425
Mar 27 at 21:28
It has not yet been answered - please refer to my comments, thank you.
– Peter Weyand
Mar 27 at 21:29
Thanks...I mean this works, but...it feels like a backdoor hack a little bit. Why can't I just query the comment by id directly? I think doing it this way requires A) obv. passing another id and B) I think searching Post when I don't have to which is another query.
– Peter Weyand
Mar 27 at 21:14
Thanks...I mean this works, but...it feels like a backdoor hack a little bit. Why can't I just query the comment by id directly? I think doing it this way requires A) obv. passing another id and B) I think searching Post when I don't have to which is another query.
– Peter Weyand
Mar 27 at 21:14
if you check the database, mongodb doesn't save the data in comment field like you are searching "comments._id", It save in the format something like "$ref" : "comment", "$id" : ObjectId("commentid"), "$db" : "dbname"
– user1361425
Mar 27 at 21:16
if you check the database, mongodb doesn't save the data in comment field like you are searching "comments._id", It save in the format something like "$ref" : "comment", "$id" : ObjectId("commentid"), "$db" : "dbname"
– user1361425
Mar 27 at 21:16
I don't believe that is correct. Here is the terminal output of a post:
flags: 0, lastFlag: 2019-03-27T21:00:54.316Z, fileName: '1553720454192&&hotdog.png', imageBanned: false, board: 'nsfw', comments: [ flags: 0, lastFlag: 2019-03-27T21:01:03.540Z, imageBanned: false, fileName: '1553720463408&&hotdog.png', _id: 5c9be48f0556ec5397cb62a2, body: 'dadf', created: 2019-03-27T21:01:03.540Z, __v: 0 ], _id: 5c9be4860556ec5397cb62a1, body: 'dog', created: 2019-03-27T21:11:15.575Z, __v: 0
– Peter Weyand
Mar 27 at 21:21
I don't believe that is correct. Here is the terminal output of a post:
flags: 0, lastFlag: 2019-03-27T21:00:54.316Z, fileName: '1553720454192&&hotdog.png', imageBanned: false, board: 'nsfw', comments: [ flags: 0, lastFlag: 2019-03-27T21:01:03.540Z, imageBanned: false, fileName: '1553720463408&&hotdog.png', _id: 5c9be48f0556ec5397cb62a2, body: 'dadf', created: 2019-03-27T21:01:03.540Z, __v: 0 ], _id: 5c9be4860556ec5397cb62a1, body: 'dog', created: 2019-03-27T21:11:15.575Z, __v: 0
– Peter Weyand
Mar 27 at 21:21
If your question has been answered, please make sure to accept answer for further references.
– user1361425
Mar 27 at 21:28
If your question has been answered, please make sure to accept answer for further references.
– user1361425
Mar 27 at 21:28
It has not yet been answered - please refer to my comments, thank you.
– Peter Weyand
Mar 27 at 21:29
It has not yet been answered - please refer to my comments, thank you.
– Peter Weyand
Mar 27 at 21:29
|
show 4 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55386030%2fmongodb-cant-query-subdocument-by-id-returns-null%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Possible duplicate of Mongoose String to ObjectID
– amcgregor
Mar 28 at 17:11
…or Mongoose saved _id's as string instead of ObjectId or Mongoose sometimes save ObjectId as string… — while these relate to the data storage side of the problem, every single one features the solution.
– amcgregor
Mar 28 at 17:22