Mongoose findOne function not being executed - node.js

... (... = some unrelated code)
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/test');
...
dataSchema = new Schema({
'url': { type: String, index: true },
'user_id': { type: Schema.ObjectId, index:true }
});
var Website = mongoose.model('websites', dataSchema);
...
Website.findOne({url: "someurl.com"},function (err, docs) {
console.log(docs._id);
});
...
For some reason the console.log does not execute. Is there anyway to tell if I am setting up my schema correctly or see if my find function failed or any sort of indication of where the problem might be? Currently, when I run my script, no errors occur, but nothing is printed out either.
Thanks!

You can check for connection and schema errors by hooking the error event on the connection as:
mongoose.connection.on('error', function(err) {
console.error('MongoDB error: %s', err);
});

Related

object referencing/mongoose-mongodb

I have been taking colt Steeles's web development bootcamp classes,so i am on the associations topic. tried writing code to do a one to many association via object referencing, the code appears thus
var mongoose= require("mongoose");
mongoose.connect("mongodb://localhost/blogApp_demo_2",{useNewUrlParser:true});
var postSchema= new mongoose.Schema({
title:String,
content:String
});
var post= mongoose.model("post",postSchema);
var userSchema = new mongoose.Schema({
name: String,
Email:String,
posts:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"post"
}]
});
var user= mongoose.model("user",userSchema);
post.create(
{
title:"beauty in the lilies",
content: "there is so much to marvel in lilies"
}, function(err,post){
user.findOne({email:"deleomoarukhe#yahoo.com"}, function(err,foundUser){
if(err){
console.log(err);
} else{
foundUser.posts.push(post);
foundUser.save(function(err,data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
}
});
});
but on trying to execute this code it gives me this error
TypeError: Cannot read property 'posts' of null
tried everything i can to get this code running, to no avail.
p.s the code was to add a further comment to an already existing user.

Can't create a collection in MongoDB datatbase

Using this code to create a collection on MongoDB database hosted on mlab. But somehow it does not seems to be working. Is there something I am missing in this code? .save() function does not seem to be firing at all. Can it be due to my schema?
var mongoose= require('mongoose');
var Schema= mongoose.Schema;
app.use(express.static(__dirname+'/views'));
app.use(express.static(path.join(__dirname, 'public')));
//connect to mongo db database
mongoose.connect('mongodb://blaa:blaa#ds127132.mlab.com:27132/vendor');
//vendor schema
var vendorSchema= new Schema({
name:String,
image: { data: Buffer, contentType: String },
vendortype:String,
location: {
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
},
contactinfo:String,
description:String
});
//creating a model for mongoDB database
var Vendor= mongoose.model('Vendor',vendorSchema);
//just putting a sample record data
var imgPath = 'public/images/background.jpg';
var one = Vendor({
name: 'Justin Motor Works',
vendortype: 'Automobile',
contactinfo:'6764563839',
location: {
type:[23.600800037384033,46.76758746952729]
},
image: {
data: fs.readFileSync(imgPath),
contentType: 'image/jpg'
},
description: 'Motor workshop'
}).
save(function(err){
if(err)
throw err;
else {
console.log('create record failed');
}
});
mongoose.connect is an asynchronous function, you need to put your code inside a callback or promise.then(function(){.
Try this:
mongoose.connect('mongodb://blaa:blaa#ds127132.mlab.com:27132/vendor', function(error) {
if (error)
//handle error
//Your code
});
Or this:
mongoose.connect('mongodb://blaa:blaa#ds127132.mlab.com:27132/vendor').then(
() => {
//Your code
},
err => {
//Your error handling
}
);
Notice the error handling, it's important to know what caused the error for future debugging.
Also change the JSON structure of location when you are saving it as #NeilLunn said in the comments to something like this:
location: [23.600800037384033,46.76758746952729],
type in mongoose means actually defining the type of the key, and not a nested type key.

Node.JS Express 4 - Mongoose Does not saving data

I am trying to save a data in MongoDB with Mongoose with Express.JS 4 and Bluebird.
What I have done is like this-
bin/www
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
.......
.......
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function()
{// successfully connected!
console.log("Successfully Connected to Mongo-DB");
});
And getting this in console-
Successfully Connected to Mongo-DB` - So, MongoDB connected successfully
models/post.js
var mongoose = require('mongoose');
var postSchema = new mongoose.Schema({
created_by: String, //should be changed to ObjectId, ref "User"
created_at: {type: Date, default: Date.now},
text: String
});
module.exports = mongoose.model('Post', postSchema);
app.js
var Post_Data = require("./models/post");
....
....
router.get('/', function(req, res, next)
{
var Post = mongoose.model("Post");
var post = new Post({
created_by: ""+Math.random()
});
console.log( Post.create(post) );
res.render(
'index',
{
title : 'Express',
site_name : 'Our Site',
layout : 'templates/layout'
}
);
});
And after that I am getting this in console-
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
But, nothing is saved, a proof for that is -
I am finding this-
After using MongoBooster.
Update-
My DB config is like this-
"MONGO_URI": "mongodb://localhost:27017/express_test",
"MONGO_OPTIONS": {
"db": { "safe": true },
"name":"express_test"
}
So, can anyone please help, why it is not saving anything?
Thanks in advance for helping.
The .create() function is a shortcut for new Model and .save(). You are trying to .create an instance of Model rather than a simple Object. See Constructing documents in Mongoose's Models documentation for their quick example.
The return from a Mongoose data function is just the promise of an asynchronous task to be run in the future, logging that is largely pointless. Use .then() to wait until the promise has been resolved.
Error handling is missing from your code as well, something could be getting thrown there. Use a .catch() for promise error handling.
Post.create({ created_by: ""+Math.random() })
.then(function (result) {
console.log('Saved' result)
})
.catch(function (err) {
console.error('Oh No', err)
})
All of this can be done with callbacks (like the Mongoose docco examples) but promises, particularly bluebird promises are nicer.
I just use this syntax combination to create and save my model:
var myPage = new LandingPage({
user:req.user,
slug: req.body.slug,
}).save(function(err,savedModel){
if(!err){
console.log(savedModel);
}
});
You are calling the wrong model in your app.js module as you are importing the model as
var Post_Data = require("./models/post"); // <-- Post_Data model never used
....
....
but creating a new Post model instance in your router implementation as
var Post = mongoose.model("Post"); // <-- different model
var post = new Post({
created_by: ""+Math.random()
});
You need to call and use the correct models. So I would suggest you re-write your app.js module to use the save() method as:
var Post = require("./models/post"); // <-- import correct Post model
....
....
router.get('/', function(req, res, next) {
var post = new Post({ created_by: ""+Math.random() });
post.save().then(function(post) {
console.log(post); // <-- newly created post
res.render('index', {
title: 'Express',
site_name: 'Our Site',
layout: 'templates/layout'
});
})
.catch(function(err) {
console.error('Oopsy', err);
});
});
if you store post schema in a variable by require then can use that variable.
var Post_Data = require("./models/post");
so can use new Post_Data no need to use var Post = mongoose.model("Post"); because you have already exported this schema module.exports = mongoose.model('Post', postSchema);
you can try this one :
var Post_Data = require("./models/post");
router.get('/', function(req, res, next)
{
var post = new Post_Data({created_by: ""+Math.random()});
post.save(function(error, data) {
if(error) {
return res.status(500).send({error: 'Error occurred during create post'});
}
return res.render('index',{
title : 'Express',
site_name : 'Our Site',
layout : 'templates/layout'
});
});
});
So it's true that if you're creating a document in memory by calling new Post(values) that you will save it with post.save(cb); rather than 'Post.create(post);, but I'm thinking that the underlying issue (though this isn't easy to be certain of based on the code you're showing) is that you're connecting with the MongoDB driver, rather than mongoose itself. Yourdb` variable isn't shown to be declared in the code you posted, so I'm making it an assumption.
That said, if I'm right, you need to call mongoose.connect or mongoose.createConnection in order for Mongoose to know it's connected to the db and save documents to it. You can pass an existing connection to mongoose, so if you're already doing so then I apologize for my erroneous assumption.

I am getting an error of mongoose is not defined

I am creating an api using MongoDB, I am using Mongoose to create Data Persistence. However I am getting an error that Mongoose is not defined, I have used require function to call the node module but it is still giving me the same error.
Below is the connection file
var mongoose = require('mongoose')
var database = 'api'
const server = 'mongodb://localhost:27017/'+database
console.log(server)
mongoose.connect(server)
const db = mongoose.connection
console.log(db)
var Schema = mongoose.Schema
var ObjectId = Schema.ObjectId
const WeatherSchema = new Schema({
id: {type: String, required: true},
name: { type: String, required: true },
items: {type: String, required: true}
})
var WeatherDB = mongoose.model('DBlist', WeatherSchema)
You should wait for the database to connect, as it doesn't happen immediately. Something like this:
var mongoose = require('mongoose');
mongoose.connect(sever);
var db = mongoose.connection;
db.on('disconnect', connect); // auto reconnecting
db.on('error', function(err) {
debug('connection error:', err);
});
db.once('open', function (callback) {
// we're in the game, start using your Schema
const WeatherSchema = new Schema({...
});
p.s.
I've added little extra sugar just to let you know these events exist and are quite helpful to understand what's going on.

Mongoose save callback doesn't fire

I'm new to mongoose and I'm having a hard time finding the issue within my code. I'm building a REST server using Sails.js and Mongoose. I have a node module (e.g. "sails-mongoose") for exporting mongoose, where I also connect to my database:
var mongoose = require('mongoose');
mongoose.connect('mongodb://#localhost:27017/fooria');
module.exports = mongoose;
And in my model.js:
var adapter = require('sails-mongoose');
var schema = new adapter.Schema({
firstname: {
type: String,
required: true,
trim: true
}
});
module.exports = {
schema: schema,
model: adapter.model('Collection', schema)
}
In my controller's create method I have:
create: function(req, res, next) {
var userData = {firstname: 'Test'};
var users = new Users.model(userData);
users.save(function(err, data){
if (err) return res.json(err, 400);
res.json(data, 201);
});
}
When running create method, the entry is saved to the Mongodb collection but the callback is never reached. Can someone please help me on this track, as I found similar questions but none helped me though. Thanks!
I suppose your are using Express. According Express docs you are calling res.json using incorrect parameters (wrong order).
Correct format:
res.json(code, data)
Example:
res.json(500, { error: 'message' })

Resources