Mongoose query middleware/pre-find hooks, what does 'this' refer to? - node.js

I have been learning about mongoose query middleware and that when using this within a query middleware function it refers to the query object.
However, I am struggling to visualise what the query object actually is and how I can use it. For example, if I had the code:
let query = Model.findById(req.params.id);
If I were then to use query middleware:
tourSchema.pre(/^find/, function (next) {
console.log(this)
next();
});
What would this be?

As explained into docs
In query middleware functions, this refers to the query.
Also, if you do a console.log(this) you can check the object is like:
Query {
//a lot of stuffs
}
So, that is, this is the query.
Also, as another example, using update you can do this query:
model.update({},{$set:{field:"value"}})
And check this hook:
MongooseModel.pre('update', async function () {
const query = this.getUpdate();
console.log(query) // { '$set': { field: 'value' } }
const field = query.$set.field;
console.log(field) // value
});

Related

Mongoose Model.find() methods query string not working

im trying to make simple rest api. I have a collection in mongodb and i connected my db to my app with mongoose pkg. I can access all items without query strings with Operator.find() but it doesn't work with query string ex: Operator.find({name:'Kapkan'}) it returns all of them. Also Operator.findOne({name:'Azami'}) doesn't work either. The query string returns the first element of the collection no matter what.
app.get('/api/operators',async(req,res) => {
let operators;
try{
if(req.query.name){
Operator.find({name:'Kapkan'}).then((data) => {
console.log(data);
});
}
else
operators = await Operator.find();
res.send(operators)
}catch(er){
console.log(er);
}
})
You are not assigning result of query with filter to operators. Unsure if you have {} around else or not but try refactoring the code as shown below:
app.get('/api/operators',async(req,res) => {
const filters = {};
if (req.query.name) {
filters.name = req.query.name;
}
const data = await Operator.find(filters);
console.log(data);
return res.json({ data });
})
I checked my Schema and i realize i forgotten put name field...
const OperatorSchema = new Schema({
_id:Number,
logo:String,
image:String,
unit:String,
*name:String,
side:String,
.
.
.
})

Prevent _id field from being supplied in a MongoDB query

I'm using Mongoose in NodeJS to control a MongoDB database.
I'm creating an API and for obvious security reasons, I want to prevent the auto generated document _id field from getting replaced by a manually generated one in the API request.
Schema:
{ name: String }
Creating a document:
const record = {
_id: '5e35517cc894c90327a34baf'
name: 'bob'
}
const insertRecords = async () => {
await Quiz.create(record);
};
insertRecords();
Results in the following document:
{
_id: '5e35517cc894c90327a34baf'
name: 'bob'
}
As can be seen, the _id supplied in the query, as long as it's a valid ObjectID, would replace the _id that was supposed to be auto generated by mongo.
Is there a way to check if this _id field is in the query so that I can reject the API request? The .create method triggers the pre save middleware hook which would always have the _id of the final document so I cannot depend on it to know whether the _id was in the query or it's the auto generated one.
The only option I found is to disable the _id field altogether but this does not make sense.
Solution #1 - Use .create() method with an explicit object.
It's actually easier than you think. This is self-explanatory - we only define what we want to allow. Mongoose will ignore anything that's not in the object.
const record = {
_id: '5e35517cc894c90327a34baf'
name: 'bob'
}
const insertRecords = async () => {
await Quiz.create({
name: record.name // only allow names.
});
};
insertRecords();
Solution #2 - Define a function to clear unwanted objects.
You can define a helper function to clear out unwanted fields.
const filterObj = (obj, ...allowedFields) => {
const newObject = {};
// If the current field is one of the allowed fields, keep them in the new object.
Object.keys(obj).forEach((el) => {
if (allowedFields.includes(el)) {
newObject[el] = obj[el];
}
});
return newObject;
};
How to use:
const filteredRecord = filterObj(record, 'name'); // arbitrary list of allowed fields. In this case, we'll only allow 'name'.
await Quiz.create(filteredRecord);

Mongoose find and findById inconsistency

I'm testing mongoose queries, and I found this bizarre behaviour. I have a document with _id: "5de64b376c79643fa847e86b", and if I call the findById method the document is returned just fine. But if I call the find method on the collection, giving as args an array with the same ID value than nothing is returned, while I expect an array of one element being the document. To summarize:
mongooseModel.findById(mongoose.Types.ObjectId("5de64b376c79643fa847e86b")) // Works
mongooseModel.find({ _id: { $in: [mongoose.Types.ObjectId("5de64b376c79643fa847e86b")] } }) //Doesn't work
What's the difference between the two, and why the second one doesn't work?
EDIT: This is kinda the code to access that method.
I define a DataSource in the ApolloServer configuration
const app = new ApolloServer({
...
dataSources: () => ({
source: new SourceAPI(DocumentModel)
})
...
});
where SourceAPI is the DataSource class and DocumentModel is the mongoose model.
SourceAPI is defined like this
class SourceAPI {
async get(ids) {
return await DocumentModel.find({
_id: {
$in: ids
}
});
}
}
Now, inside the GraphQL resolver I finally call the API method to get the documents, like this
const findResolver = () =>
DocumentSchema.get("$findById").wrapResolve(next => async rp => {
let ids = [];
ids.push(mongoose.Types.ObjectId(rp.args._id));
return await rp.context.dataSources.source.get(ids);
});
where DocumentSchema is the GraphQL Schema for the Document Model generated using graphql-compose-mongoose package. The get("$findById") and wrapResolve methods are also from that package. What I do is using these methods to get the GraphQL query parameters and pass them to the API method (in this case I'm just grabbing an ID for test).
If I change the API method to something like this
async get(id) {
return await DocumentModel.findById(id);
}
and the resolver method to this
const findResolver = () =>
DocumentSchema.get("$findById").wrapResolve(next => async rp => {
return await rp.context.dataSources.source.get(mongoose.Types.ObjectId(rp.args._id));
});
everything works
$in is used to find items which holds an array, but _id is just a JSON key/value pair. So you cannot use $in. If your object looks like this then you can use $in
{
id: [ObjectId("5de64b376c79643fa847e86b"),
ObjectId("5de64b376c79643fa847e86b")]
}

How to use MongoDB findOne() with mongoose

I'm having troubles using the MongoDB findOne() function together with mongoose.
controller
exports.show = function (req, res) {
Fahrt.load(req.params.fahrtenId, function (err, fahrt) {
res.jsonp(fahrt);
});
};
model
FahrtSchema.statics = {
load: function (id, cb) {
this.findOne({
_id: id
}
).exec(cb);
}};
route
router.get('/:fahrtId', fahrtenController.show);
app.js
app.use('/fahrten', fahrten);
When I use Postman to query for a "Fahrt"Object with a specific ID I get back "null". When I search with the Mongo Console directly via
db.Fahrt.findOne({"_id": ObjectId("5562ca06a14c4924090ba5ff")})
I get an existing object and everything is as expected. But why not when I query via Mongoose?
The parameter in your route is :fahrtId:
router.get('/:fahrtId', fahrtenController.show);
But you are trying to retrieve the value from fahrtenId:
req.params.fahrtenId

NodeJS + MongoDB: Getting data from collection with findOne ()

I have a collection "companies" with several objects. Every object has "_id" parameter. I'm trying to get this parameter from db:
app.get('/companies/:id',function(req,res){
db.collection("companies",function(err,collection){
console.log(req.params.id);
collection.findOne({_id: req.params.id},function(err, doc) {
if (doc){
console.log(doc._id);
} else {
console.log('no data for this company');
}
});
});
});
So, I request companies/4fcfd7f246e1464d05000001 (4fcfd7f246e1464d05000001 is _id-parma of a object I need) and findOne returns nothing, that' why console.log('no data for this company'); executes.
I'm absolutely sure that I have an object with _id="4fcfd7f246e1464d05000001". What I'm doing wrong? Thanks!
However, I've just noticed that id is not a typical string field. That's what mViewer shows:
"_id": {
"$oid": "4fcfd7f246e1464d05000001"
},
Seems to be strange a bit...
You need to construct the ObjectID and not pass it in as a string. Something like this should work:
var BSON = require('mongodb').BSONPure;
var obj_id = BSON.ObjectID.createFromHexString("4fcfd7f246e1464d05000001");
Then, try using that in your find/findOne.
Edit: As pointed out by Ohad in the comments (thanks Ohad!), you can also use:
new require('mongodb').ObjectID(req.params.id)
Instead of createFromHexString as outlined above.
That's because _id field in mongo isn't of string type (as your req.params.id). As suggested in other answers, you should explicitly convert it.
Try mongoskin, you could use it like node-mongodb-native driver, but with some sugar. For example:
// connect easier
var db = require('mongoskin').mongo.db('localhost:27017/testdb?auto_reconnect');
// collections
var companies = db.collection('companies');
// create object IDs
var oid = db.companies.id(req.params.id);
// some nice functions…
companies.findById();
//… and bindings
db.bind('companies', {
top10: function(callback) {
this.find({}, {limit: 10, sort: [['rating', -1]]).toArray(callback);
}
});
db.companies.top10(printTop10);
You can use findById() which will take care of the id conversion for you.
company = Company.findById(req.params.id, function(err, company) {
//////////
});
In case these didn't work for you, this worked for me for accessing a blog post:
const getSinglePost = async (req, res) => {
let id = req.params.id;
var ObjectId = require('mongodb').ObjectId;
const db = await client.db('CMS');
const data = await db.collection("posts").findOne({ _id: ObjectId(id) })
if (data) {
res.status(200).send(data)
} else res.status(400).send({ message: "no post found" })
}

Resources