Fetching collections via Mongoose fails(Object {} has no method 'find') - javascript

I want to fetch some collections via Mongoose find method. My model is like this:
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
timeline_content: String,
timeline_e_id: String
});
var timeline = mongoose.model('timeline', schema);
module.exports = timeline;
and with this code i want to fetch some collections:
var Timeline = require('./models/timeline');
var timeline = new Timeline();
timeline.find({timeline_e_id:'an id'}).sort("_id").limit(5).exec(
function(err, projects) {
if (err) {
throw err;
}
//do something
}
);
But i get this error:
TypeError: Object {} has no method 'find'
Why? i have to define find method inside my model? Actually i can't find any resource to do queries. This is simplest one but it fails.

.find is a method on your TimeLine model, not on an instance of TimeLine.
Drop the new and the () from your variable assignment.
EDIT
As suggested by Blakes Seven, your code should look like this:
var Timeline = require('./models/timeline');
TimeLine.find({timeline_e_id:'an id'}).sort("_id").limit(5).exec(
function(err, projects) {
if (err) {
throw err;
}
//do something
});

Related

Model.create() from Mongoose doesn´t save the Documents in my Collection

I have created a sigle app with a Schema and a Model to create a Collection and insert some Documents.
I have my todoModel.js file:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const todoSchema = new Schema({
username: String,
todo: String,
isDone: Boolean,
hasAttachment: Boolean
});
const Todos = mongoose.model("Todo", todoSchema);
module.exports = Todos;
Then I have created a setUpController.js file with a sample of my Documents. Then I create a Model and I pass my sample of Documents and my Schema. I create a response to send tje result in JSON.
Everything good here, as I get the result in json when accessing to the route.
Here is the code:
Todos.create(sampleTodos, (err, results) => {
if (!err) {
console.log("setupTodos sample CREATED!")
res.send(results);
}
else {
console.log(`Could not create the setupTodos Database sample, err: ${err}`);
}
});
My problem is that this Documents don´t get saved in the collection !! When I access to the database, nothing is there.
This is my app.js file:
mongoose.connect("mongodb://localhost:27017/nodeTodo")
.then(connection => {
app.listen(port);
})
.catch(err => {
console.log(`Could not establish Connection with err: ${err}`);
});
Could anyone help me please ?
Thank you
Try creating an instance and making the respective function call of that instance. In your case, save the document after creating an instance and it works like a charm.
const newTodos = new Todos({
username: "username",
todo: "todos",
isDone: false,
hasAttachment: flase
});
const createdTodo = newTodos.save((err, todo) => {
if(err) {
throw(err);
}
else {
//do your staff
}
})
after the collection is created you can use the function inserMany to insert also a single document the function receives an array of objects and automatically saves it to the given collection
example:
Pet = new mongoose.model("pet",schemas.petSchema)
Pet.insetMany([
{
//your document
}])
it will save only one hardcoded document
I hope it was helpful

save method in Mongoose failed

I tried to use save() in Mongoose but saw empty collection been inserted.
my photo schema is like this :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var photosSchema = mongoose.Schema({
photos: {
type: String
},
caption: {
type: String
}
});
var Photos = module.exports = mongoose.model('photos', photosSchema);
module.exports.getAllPhotos = function(callback){
Photos.findAll(callback);
}
and in my route I do
var Photo = require('../models/photos');
router.post('/upload_photo', upload.any(), function(req, res, next) {
var photo = new Photo();
var data = {
photos:'abc.jpg',
caption:'something..'
}
photo.save(data);
res.end();
});
Am I using save wrong here? I know I can define a method like savePhoto and export it, but how to use save() directly instead?
Try it like so, i.e. pass the data directly to the constructor and end the response stream when the async. save finished (and maybe add error handling as well).
var photo = new Photo({
photos:'abc.jpg',
caption:'something..'
});
photo.save(function(err) {
res.end();
});
There is also a shorthand create method on the model as described in the Mongoose docs
Try like this, and you will be able to see the issue if there's any:
var data = {
photos:'abc.jpg',
caption:'something..'
};
var photo = new Photo(data);
photo.save(function (err) {
if (err) console.log(err);
res.end();
});

How to get Mongoose to list all documents in the collection? To tell if the collection is empty?

I'm using a MEAN stack and writing these methods in Mongoose. I'm wondering what's wrong with what I put in the Mongoose model file. I would like to use Mongoose to simply print out a list all the documents in the myModel collection.
myModel.methods.myMethod = function(cb){
this.model("Bids").find({}, 'myField', function(err, results){
if (err){console.log(err);return err;}
console.log("okay");
console.log(results);
})
this.save(cb);
}
Also, what is the code that I can write in Mongoose to tell if the myModel collection is empty or not?
It's better to teach a man how to fish than to give him a fish ...
So it would be extremely helpful if you can suggest what debugging tools I can install, such as an Express middleware, that can help me debug myself. Please post your debugging suggestions here.
I'm assuming every other setup required for mongoose is correct.
At the line below, I think 'myField' is not needed.
this.model("Bids").find({}, 'myField', function(err, results)
Here is something more from scratch, maybe it would help you to trace-back you steps:
var mongoose = require('mongoose');
//connection to Mongodb instance running on=======
//local machine or anywhere=========================
var uri = 'mongodb://localhost:27017/test';
var connection = mongoose.createConnection(uri);
//Define Schema==================================
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
author: { type: Schema.Types.ObjectId },
title: String,
body: String
});
//Create model===================================================
var BlogPostModel = connection.model('BlogPost', BlogPostSchema);
//function to insert doc into model NOTE "pass in your =======
//callback or do away with it if you don't need one"=========
var insertBlogPost = function (doc, callback) {
//here is where or doc is converted to mongoose object
var newblogPost = new BlogPostModel(doc);
//save to db
newblogPost.save(function (err) {
assert.equal(null, err);
//invoke your call back if any
callback();
console.log("saved successfully");
});
};
//function to get all BlogPosts====================================
var getAllBlogPosts = function (callback) {
//mongoose get all docs. I think here answers your question directly
BlogPostModel.find(function (err, results) {
assert.equal(null, err);
//invoke callback with your mongoose returned result
callback(results);
});
};
//you can add as many functions as you need.
//Put all of your methods in a single object interface
//and expose this object using module.
var BlogPostManager = {
insertBlogPost: insertBlogPost,
getAllBlogPosts : getAllBlogPosts
}
module.exports = BlogPostManager;

TypeError: undefined is not a function in Node.js

In my Group model, I'm exporting one function that pass the result of a query using a callback.
In my router file, I'm calling this function, after properly requiring the other file.
That's my ./models/groups.js:
var groupSchema = new mongoose.Schema({
[...]
module.exports.getAll = function(cb) {
groupSchema.find({}, function(err, groups) {
if (err) return cb(err)
cb(null, groups)
})
}
[...]
module.exports = mongoose.model('Group', groupSchema);
and that's my ./routes/groups.js file.
var Group = require('../models/group')
router.route('/groups')
.get(function(req, res, next) {
Group.getAll( function(err, group){
if (err) res.send(err)
res.send(group)
})
})
[...]
This is not working, because every time I make a get request, I'm getting a TypeError: undefined is not a function error. I know I can make the query right on my router file, but I think separating things between routes and methods would be a better practice.
You're overwriting the object where you defined the getAll function when you assign a new value to module.exports.
You've got 2 options:
Extend the model with the getAll function, and export as you do today.
This basically looks like:
var model = mongoose.model('Group', groupSchema);
model.getAll = function(cb) {
...
};
module.exports = model;
But that's not very "clean".
Export the model under a named property alongside the getAll function.
This basically looks like this:
module.exports.getAll = function(cb) {
...
};
module.exports.model = mongoose.model('Group', groupSchema);
Then in your routes, you'd have:
var Groups = require('../models/group');
// Now you have Groups.getAll & Groups.model
This is more flexible overall and will allow you to export other types/functions/values as you see fit.

What is the correct way of passing a Mongoose object into the MongoDB underlying connection insert() method

I need to insert many thousands of documents into MongoDB. I want to use Mongoose for its casting properties, etc. However I cannot figure out how to pass the generated instances to the MongoDB connection. I have tried this:
var fs = require('fs');
var mongoose = require('mongoose');
var config = JSON.parse(fs.readFileSync("./config.json"));
mongoose.connect(config.mongoDBUrl);
db = mongoose.connection;
db.once('open', function () {
var TestSchema = new mongoose.Schema({
testStr : String
});
var Model = mongoose.model('test_schema_2', TestSchema);
var inst = new Model();
inst.testStr = "EWAFWEFAW";
// This works.
db.collection('test_schema_2').insert({ testStr : 'My Test Str'}, {}, function (err) {
if (err) {
console.log(err);
} else {
console.log('Written.');
db.close();
}
});
// This doesn't.
db.collection('test_schema_2').insert(inst, {}, function (err) {
if (err) {
console.log(err);
} else {
console.log('Written.');
db.close();
}
});
});
In the second case, I get: "[RangeError: Maximum call stack size exceeded]"
What is Mongoose breaking behind the scenes that stops this from working, and how can I make it work?
To save an instance of a model you just have to do
inst.save(function(err) {
//Do something here
});

Categories

Resources