Mongoose - Save function does nothing - node.js

I'm learning Mongoose, and I got a bug while saving a user. This is my User Model :
This is my route :
The MongoDB connection is correct, I see it in the console, and Postman only shows a Loading Page..
I don't know why it is not working.
Thanks in advance!

I resolved it.
My MongoDB Connection url was :
mongodb://localhost:27017/alexcaron
I've just updated it to
mongodb://localhost/alexcaron

Based on what you explained, and without more logging data, using Mongoose 4.4.12, the word new maybe?
https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js#L14
var mongoose = require('mongoose'),
User = require('./models/users_model');
For using user:
var user = new User({
courriel: "test1",
password: "test2"
});

Related

MongoError - Authentication error (password with #)

Here is my code in my NodeJS application, to connect to my MongoDB engine :
const collection = 'mynewcollection';
const password = 'passwordwithan#';
const mongoUrl = `mongodb://admin:${encodeURIComponent(password)}#mymongobase.net/${collection}`;
// Connect using the connection string
MongoClient.connect(mongoUrl, {useNewUrlParser: true}, function(err, db) {
console.log(err.toString())
});
I get an authentication error. I tried several things to handle the '#' character and reading the documentation I thought that it was the good one...
But it is still failing even if the user and password are the good one.
Is the API correctly used ? Do you understand what is wrong ?
Thanks in advance.
OK I found the solution.
If you use :
const mongoUrl = `mongodb://admin:${encodeURIComponent(password)}#mymongobase.net/${collection}`;
Mongo will try to connect with admin/password defined on the collection.
If you don't put the collection in the mongo url :
const mongoUrl = `mongodb://admin:${encodeURIComponent(password)}#mymongobase.net`;
Then you can use the super user defined on all the mongo engine.

.find() returns empty when used with node.js and mongoose but returns data on mongo shell [duplicate]

I have tried using find and findOne and both are not returning a document. find is returning an empty array while findOne is returning null. err in both cases in null as well.
Here is my connection:
function connectToDB(){
mongoose.connect("mongodb://localhost/test"); //i have also tried 127.0.0.1
db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function callback(){
console.log("CONNECTED");
});
};
Here is my schema:
var fileSchema = mongoose.Schema({
hash: String,
type: String,
extension: String,
size: String,
uploaded: {type:Date, default:(Date.now)},
expires: {type:Date, default:(Date.now()+oneDay)}
});
var Model = mongoose.model("Model", fileSchema);
And my query is here:
Model.find({},function(err, file) {
console.log(err)
console.log(file);
});
I can upload things to the database and see them via RockMongo but I cannot fetch them after. This my first time using MongoDB so I think I'm just missing some of the fundamentals. Any push in the right direction would be great!
The call to mongoose.model establishes the name of the collection the model is tied to, with the default being the pluralized, lower-cased model name. So with your code, that would be 'models'. To use the model with the files collection, change that line to:
var Model = mongoose.model("Model", fileSchema, "files");
or
var Model = mongoose.model("file", fileSchema);
Simply inorder to avoid pluralization complexity use this:
var Model = mongoose.model("Model", fileSchema, "pure name your db collection");
It's very confusing.[at least for me.]
Had kinda same problem. The solutions above didnt work for me. My app never returns error even if the query is not found. It returns empty array. So i put this in my code:
if(queryResult.length==0) return res.status(404).send("not found");
This issue is probably coming from the fact that you are creating a mongoose model without specifying the name of the collection.
Try changing : const Model = mongoose.model("Model", fileSchema);
To this : const Model = mongoose.model("Model", fileSchema, "NameOfCollection");
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
I had a space in 'Growing Unit' on purpose and it always returned empty array. Removing that space to become 'GrowingUnit' was the fix needed in my scenario.
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
General "hello world" issues (Sometimes this issue not related to mongoose).
Check if the collection is not really empty (mongoDB atlas screenshot).
Check for small spelling differences (Like listing instead of listings) in your collection queries commands.
Check if you use the correct URI for your connection (For example you are trying to retrieve data from a collection that exists in localhost but use mongoDB cluster (Cloud) -or- any other issue related to Connection String URI).
https://docs.mongodb.com/manual/reference/connection-string/
For me the issue was .skip(value), I was passing page=1 instead of page=0.
As I was having few records, I was getting empty array always.

Cannot fetch data from MongoDB using Mongoose [duplicate]

I have tried using find and findOne and both are not returning a document. find is returning an empty array while findOne is returning null. err in both cases in null as well.
Here is my connection:
function connectToDB(){
mongoose.connect("mongodb://localhost/test"); //i have also tried 127.0.0.1
db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function callback(){
console.log("CONNECTED");
});
};
Here is my schema:
var fileSchema = mongoose.Schema({
hash: String,
type: String,
extension: String,
size: String,
uploaded: {type:Date, default:(Date.now)},
expires: {type:Date, default:(Date.now()+oneDay)}
});
var Model = mongoose.model("Model", fileSchema);
And my query is here:
Model.find({},function(err, file) {
console.log(err)
console.log(file);
});
I can upload things to the database and see them via RockMongo but I cannot fetch them after. This my first time using MongoDB so I think I'm just missing some of the fundamentals. Any push in the right direction would be great!
The call to mongoose.model establishes the name of the collection the model is tied to, with the default being the pluralized, lower-cased model name. So with your code, that would be 'models'. To use the model with the files collection, change that line to:
var Model = mongoose.model("Model", fileSchema, "files");
or
var Model = mongoose.model("file", fileSchema);
Simply inorder to avoid pluralization complexity use this:
var Model = mongoose.model("Model", fileSchema, "pure name your db collection");
It's very confusing.[at least for me.]
Had kinda same problem. The solutions above didnt work for me. My app never returns error even if the query is not found. It returns empty array. So i put this in my code:
if(queryResult.length==0) return res.status(404).send("not found");
This issue is probably coming from the fact that you are creating a mongoose model without specifying the name of the collection.
Try changing : const Model = mongoose.model("Model", fileSchema);
To this : const Model = mongoose.model("Model", fileSchema, "NameOfCollection");
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
I had a space in 'Growing Unit' on purpose and it always returned empty array. Removing that space to become 'GrowingUnit' was the fix needed in my scenario.
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
General "hello world" issues (Sometimes this issue not related to mongoose).
Check if the collection is not really empty (mongoDB atlas screenshot).
Check for small spelling differences (Like listing instead of listings) in your collection queries commands.
Check if you use the correct URI for your connection (For example you are trying to retrieve data from a collection that exists in localhost but use mongoDB cluster (Cloud) -or- any other issue related to Connection String URI).
https://docs.mongodb.com/manual/reference/connection-string/
For me the issue was .skip(value), I was passing page=1 instead of page=0.
As I was having few records, I was getting empty array always.

Can't find Db in mongodb while using mongoose

The following code, works exactly fine giving the output .
var mongoose=require('mongoose');
var dbUrl='mongodb://localhost:27017/trial1';
mongoose.connect(dbUrl);
//Creating schema
var userSchema=new mongoose.Schema({
name:String,
email:String,
createdOn:Date
});
mongoose.model('User',userSchema);
var User=mongoose.model('User');
var userOne=new User({name:'Mike'});
console.log(userOne.name);
mongoose.connection.on('connected',function(){
console.log('mongoose connected to '+dbUrl);
});
mongoose.connection.close(function(){
console.log('connection closed!!!!');
});
But when I try to search for the db in the connection string (ie)trial1, I am not able to find it, The screen shot is as follows.
Also when I say "use trial1" in mongo shell I'm getting the output as per the following screen shot. Which means the db exists or its been created.
Why am I not able to see that db??
So yes the answer is in the comment of Blakes and also part of answer from Pio.
You don't see the databases because your Mongoose code does not actually create any user in it. When you instantiate your Model User it will create it in memory but not in the database. To insert your user in the database you must call the method save on your instance like this:
var userOne=new User({name:'Mike'});
userOne.save(function(err, user){
if (!err) {
console.log('Now my user is saved in the database');
}
})
So if you don't save your user, then in the mongo shell you won't see the databases as it is empty and so does not exists.
what user you use to access the db, maybe the user have no auth on the db.
or, your db url should be this: mongodb://username:password#localhost:27017/trial1.
thanks.
To display a database with show dbs you need to insert at least one document into one of the db's collection. See more details here.

Mongoose always returning an empty array NodeJS

I have tried using find and findOne and both are not returning a document. find is returning an empty array while findOne is returning null. err in both cases in null as well.
Here is my connection:
function connectToDB(){
mongoose.connect("mongodb://localhost/test"); //i have also tried 127.0.0.1
db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function callback(){
console.log("CONNECTED");
});
};
Here is my schema:
var fileSchema = mongoose.Schema({
hash: String,
type: String,
extension: String,
size: String,
uploaded: {type:Date, default:(Date.now)},
expires: {type:Date, default:(Date.now()+oneDay)}
});
var Model = mongoose.model("Model", fileSchema);
And my query is here:
Model.find({},function(err, file) {
console.log(err)
console.log(file);
});
I can upload things to the database and see them via RockMongo but I cannot fetch them after. This my first time using MongoDB so I think I'm just missing some of the fundamentals. Any push in the right direction would be great!
The call to mongoose.model establishes the name of the collection the model is tied to, with the default being the pluralized, lower-cased model name. So with your code, that would be 'models'. To use the model with the files collection, change that line to:
var Model = mongoose.model("Model", fileSchema, "files");
or
var Model = mongoose.model("file", fileSchema);
Simply inorder to avoid pluralization complexity use this:
var Model = mongoose.model("Model", fileSchema, "pure name your db collection");
It's very confusing.[at least for me.]
Had kinda same problem. The solutions above didnt work for me. My app never returns error even if the query is not found. It returns empty array. So i put this in my code:
if(queryResult.length==0) return res.status(404).send("not found");
This issue is probably coming from the fact that you are creating a mongoose model without specifying the name of the collection.
Try changing : const Model = mongoose.model("Model", fileSchema);
To this : const Model = mongoose.model("Model", fileSchema, "NameOfCollection");
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
I had a space in 'Growing Unit' on purpose and it always returned empty array. Removing that space to become 'GrowingUnit' was the fix needed in my scenario.
const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
General "hello world" issues (Sometimes this issue not related to mongoose).
Check if the collection is not really empty (mongoDB atlas screenshot).
Check for small spelling differences (Like listing instead of listings) in your collection queries commands.
Check if you use the correct URI for your connection (For example you are trying to retrieve data from a collection that exists in localhost but use mongoDB cluster (Cloud) -or- any other issue related to Connection String URI).
https://docs.mongodb.com/manual/reference/connection-string/
For me the issue was .skip(value), I was passing page=1 instead of page=0.
As I was having few records, I was getting empty array always.

Resources