I'm using MongoDb
(as part of MongoJS
) in Node
. Here is the documentation for MongoJS.
I'm trying to do a call within Node based on an entry's _id
field. When using vanilla MongoDB
from the console, I can do:
db.products.find({"_id":ObjectId("51d151c6b918a71d170000c7")})
and it correctly returns my entry. However, when I do the same thing in Node, like:
db.products.find({"_id": ObjectId("51d151c6b918a71d170000c7")}, function (err, record) {
// Do stuff
});
I get ReferenceError: ObjectId is not defined
.
What is the correct protocol for doing this?
connect('mongodb://localhost/Company'); var Schema = new mongoose. Schema({ _id : String, name: String, age : Number }); var user = mongoose. model('emp', Schema); app. param('id', function(req, res, next, id){ user.
MongoDB provides a function with the name findById() which is used to retrieve the document matching the 'id' as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified 'id', it returns null.
By default, MongoDB creates an _id property on every document that's of type ObjectId. Many other databases use a numeric id property by default, but in MongoDB and Mongoose, ids are objects by default.
You can always use tried and true MongoDB and to find a document by id you could use the find or findOne methods and provide the id as the argument which would look something like this: The findByID function is useful when data needs to be retrieved using the _id field.
findByID using Mongoose. As the name suggests, the findByID method is used to find documents by specifying a certain id. By id, it means, the automatically created _id field whenever a document is created. The _id field is a unique value. So it is possible to use the value of _id to retrieve the document. We have details collection.
Mongoose is one Object Document Mapper that allows us to define objects with a strongly-typed schema that could be mapped to a MongoDB document. Mongoose provides several helper functions for CRUD operations.
You need to require the ObjectId function before using it:
var ObjectId = require('mongodb').ObjectID;
if you are using mongoose you can try this:
var mongoose = require('mongoose')
usersSchema = mongoose.model('users'),
mongoose.Types.ObjectId("<object_id>")
usersSchema.find({"_id": mongoose.Types.ObjectId("<object_id>")}, function (err, record) {
// Do stuff
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With