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
Related
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
});
I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.
When I try to run this I get:
"TypeError: Cannot read property 'find' of undefined" error return.
If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.
module.exports = function(app, db) {
app.get('/foo', (req, res)=>{
db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
};
Thanks
Paul is right, there is some issue in your code which is why it's returning null.
Here try this snippet. I'm using 2 files for demo.
model.js
const mongoose = require('mongoose');
mongoose.connect('mongo_url');
var barSchema = new mongoose.Schema({
// your schema
});
module.exports = mongoose.model('Bar', barSchema);
main.js
var BarCollection = require('./models'); // assuming both files are in same directory.
BarCollection.find({foo: {$all: ['bar']}}
,(err, item)=>{
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(item);
}
});
});
};
Basically what I am trying here is:
separate MongoDB model code in separate files
Import mongo collection in API files for CRUD operations
db.collection('barCollection') is returning null for some reason. You'll need to figure out why, it's probably somewhere else in your code since you don't have the setup logic here.
I'd look at whether mongodb was connected properly (i.e. is the db instance you're passing that function actually connected to the database), is mongodb running and available on the port you configured it with, etc.
I am creating app using nodejs, express, mongoose. And mongodb.user is the mongoose schema model and I am trying to fetch user array of objects, that query is perfect and my problem is I want to add new property for each user. I have tried as follows. But it does not add to the collection.
exports.memberlist = function(req, res) {
user.find({}).exec(function(err, collection) {
collection.forEach(function(member){
member.city = 'Colombo';
collection.push(member);
});
res.send(collection);
});
};
you can do like this
in Schema level create create virtual property
userSchema.virtual('city').get(function () {
return 'Colombo';
});
in controller level
exports.memberlist = function(req, res,next)
{
user.find({}).exec(function(err, users)
{
if(!err)
{
res.json(200, users.toObject({virtual: true}));
}
else
{
next(err);
}
});
};
By default, Mongoose doesn't allow to add a property to an object extracted from MongoDB DB. To do so, you have two alternatives :
1/ before exec statement you add a lean() method :
user.find({}).lean().exec(function(err, collection) {do whatever you want with collection}
2/ collection = collection.toObject();
I'm fairly new to MongoDB. My current code is as follows:
var app = express();
app.post('/myDB', function(req, res) {
console.log('POSTed data');
db.myDB.insert(req.body, function(err, doc) {
console.log(err);
res.json(doc);
});
})
I know that when data is inserted into MongoDB, a unique _id key:value pair is created. I would like to have access to this unique id upon data insertion.
But from what I know currently (admittedly not a whole lot), I would have to do an app.get('/myDB/:id')... (Or something similar) in order to access that unique identifier. Is there a way to do this without having to make an extra http request?
In MongoDB, with the Node.js driver, you can get the inserted id from the callback function's second parameter. The syntax is:
collection.insert(docs[[, options], callback])
where docs is a single document object or an array of documents, options is an options object and callback is a callback function to run after the record is inserted. The second paramter returns an array of documents inserted.
Thus you can retrieve the inserted id this way:
var app = express();
app.post('/myDB', function(req, res) {
console.log('POSTed data');
db.myDB.insert(req.body, {w:1}, function(err, doc) {
console.log("Record added as "+ doc[0]._id);
res.json(doc);
});
You can read more on the docs here.
I am building a web app with express, nodejs and monk. I am trying to create a page for each element of an array in my mongodb database.
That data is already in the collection called collections with the key coll_list like so:
{ "_id" : ObjectId("53dbaefd3d85d57492506f1f"), "coll_list" : [ "data_pagename1",
"data_pagename2", "data_pagename3" ] }
I thought it might be possible to loop over all the elements in coll_list with something like:
router.get('/index', function(req, res) {
var db = req.db;
var collection = db.get('collections');
collection.find( "coll_list" , function(e,docs) {
for (elems in docs) {
res.render(elems, {
elems : docs
});
}
});
});
Any suggestions or help/pointers on how to do this would be greatly appreciated.
Use req.params
router.get('/coll/:id',
function(req,res){
//access the id by req.params.id
//req.params.id will essentially be the _id of the document
//use it to obtain data from mongoDB and render the page using that data
//From the front end you make the call to /coll/<ObjectId> like
// /coll/53dbaefd3d85d57492506f1f and you get that id in req.params.id and use it to
//render data specific to that _id.
});
Thus, using a single route you would be able to create a page for every item in coll_list