I have the following code based on the quickstart from Mongoose Docs.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
var kittySchema = mongoose.Schema({
name: String
});
var kitten = mongoose.model('kitten', kittySchema);
kitten.find(function(err, kittens) {
if(err)
return console.error(err);
console.log(kittens[0].name);
});
});
What I want to do is log the name from each kitten in the DB.
The example above returns the name of the first kitten in the array with kittens[0].name but when I try to do the following:
for(var i in kittens){
console.log(kittens[i].name);
}
it returns undefined for each item in the DB.
I have tried converting the i variable to a number because it comes as a string but no luck.
How can I retrieve the property name of every item that comes with .find()?
Why dont you try this:
for(var i=0; i<kittens.length; i++){
console.log(kittens[i].name);
}
since, find returns an array i.e. kittens here, kittens.length will give the length of the kittens array.
Hope it helps.
Related
I created a table in mongodb and I want to add values to it via nodejs, this is my code:
mongoose.connect('mongodb://localhost:27017/attendances', { useNewUrlParser: true });
const Schema = mongoose.Schema;
const dataSchema = new Schema({ userId: String, date: Date, start: Date,end:Date });
const dataModel = mongoose.model("datas",dataSchema);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('connect to DB');
});
router.post('/add', (req, res) => {
const {userId,date,start} = req.body;
console.log('add',userId,date,start);
dataModel.create({userId:userId,date:date,start:start},function (err, result) {
});
dataModel.findOne({userId:userId,date:new Date().toDateString()},function(err,result){
console.log('findOne',result);
res.end(result);
})
});
He does not add my values to the table.
Where's my mistake?
This is my err:
Error: datas validation failed: start: Cast to date failed for value
"11:56:26" at path "start"
There is a more than one mistake.
First:
Your Object Validation fails. I need to know whats inside your start variable.
Second:
You use two different dates one is date variable other one is generated by querying with date:new Date().toDateString()
Third:
Javascript works asynchronously. You cannot know when your findOne triggers after object successfully created.
I'm facing a Mongoose's strange behaviour.
Let's analyse this simple stupid code.
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/sodatest', {
useMongoClient: true
});
var db = mongoose.connection;
var OriginalSchema = mongoose.Schema({
addedd: Date,
endPoint: Object,
inserted: Number,
total: Number
});
var OtherTestSchema = mongoose.Schema({
what: String,
modified_at: Date
});
var EndPointInTheDb = mongoose.model('aaa', OriginalSchema);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("we are connected!");
});
EndPointInTheDb.find({}, (err: String, exit: any) => {
console.log("Errore : " + err)
console.log(exit)
});
It fails and return
we are connected!
*********************
Error : null
[]
*********************
It fails because the collection "aaa" has 15 elements.
If I change the db "sodatest" with any other ( except for another one with a lowercase name ) and 'aaa' with another collection name, it does't care if I use the correct case, it returns a correct result.
we are connected!
*********************
Error : null
[ { _id: 59f76203592b426a16b8b32f,
modified_at: 2017-10-30T17:31:47.622Z,
last_position: 5,
what: 'CONTATOREGEOKEY',
__v: 0 } ]
*********************
(it works also with multiple elements)
I've tried to copy the db in another one,
db.copyDatabase("sodatest","Prova14")
with a name with at least an uppercase char (Prova14), but again no result.
I've checked for hours if I've misspelled a name, but really, I'm sure of it.
I can't understand why it works with any other db ( 14 others with heterogeneous schema) also if I use a schema ("OtherTestSchema" ) that does not match with the collection real schema.... but not with sodatest.
Any Idea ?
Mongoose automatically adds an 's' at the end of the collection name if one is not provided. For Example:
// This will create a collection called 'aaas' since 'aaa' is passed as the
// model name
var EndPointInTheDb = mongoose.model('aaa', OriginalSchema);
// This is how you declare your collection name with a custom collection 'aaa'
var CorrectEndPointInTheDbToCollection = mongoose.model('aaa', OriginalSchema, 'aaa');
CorrectEndPointInTheDbToCollection.find({}, function(err, docs){
console.log(docs)
})
So the initializer for mongoose is mongoose.model('model name', Schema, 'optional collection name'). Highly recommend you pass in the collection name so you know it's pointing to the right collection
I have a mongodb (simple_demo) with an employee collection inside.
I am trying to connect to node JS and list the collections inside the simple_demo db.
I tried doing this but nothing came back. it just shows [].
Am wondering if I did anything wrong?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/simple_demo');
var db = mongoose.connection;
db.on('open', function () {
console.log("connection ok");
db.db.listCollections().toArray(function (err, names) {
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
});
});
Good day
Your code works. Check your database.
var mongo = require('mongoose');
var connection = mongo.createConnection('mongodb://127.0.0.1/test');
connection.on("error", function(errorObject){
console.log(errorObject);
console.log('ONERROR');
});
var Schema = mongo.Schema;
var BookSchema = new Schema({ title : {type : String, index : {unique : true}}});
var BookModel = mongo.model('abook', BookSchema);
var b = new BookModel({title : 'aaaaaa'});
b.save( function(e){
if(e){
console.log('error')
}else{
console.log('no error')
}});
Neither the 'error', or 'no error' are printed to the terminal. What's more the connection.on 'error' doesn't seem to fire either. I have confirmed that MongoDb is running.
this is a case where you are adding the model to the global mongoose object but opening a separate connection mongo.createConnection() that the models are not part of. Since the model has no connection it cannot save to the db.
this is solved either by connecting to mongo on the global mongoose connection:
var connection = mongo.createConnection('mongodb://127.0.0.1/test');
// becomes
var connection = mongo.connect('mongodb://127.0.0.1/test');
or by adding your models to your separate connection:
var BookModel = mongo.model('abook', BookSchema);
// becomes
var BookModel = connection.model('abook', BookSchema);
I really like Aaron's answer, and thanks to him I am now on my way to fixing the issue... although I'm not there yet! Here is my particular issue:
I want to have my schema and models defined in separate files, so I can reuse them from project to project. So as an example I have a file named W8DBItem.js as follows:
var mongoose = require('mongoose');
var itemSchema = new mongoose.Schema({ name: {type: String, required: true}});
module.exports = mongoose.model('W8DBItem', itemSchema);
In my program file I do this this:
var mongoose = require('mongoose');
var W8DBItem = require('../w8/W8DBItem.js');
var dbURL ='mongodb://localhost:27017/default';
var mongoOptions = { useNewUrlParser: true, bufferCommands: false }
mongoose.connect(dbURL, mongoOptions);
var db = mongoose.connection;
// DEAL WITH CONNECTION ERROR
db.on('error', console.error.bind(console, 'connection error:'));
// PREP DATA
var aWeight = { name: "My Test Name" };
var newWeightItem = W8DBItem(aWeight);
// CONNECTION ESTABLISHED
db.once('open', function() {
console.log("Here 1")
// TRY TO SAVE
newWeightItem.save(function (err, newWeightItem) {
if (err) {
console.log("Here 2");
console.log(err);
}
else {
console.log("Here 3");
console.log(newWeightItem);
}
});
});
When I run this program I get "Here 1" but never "Here 2" or "Here 3" in the console.
From Aaron's post I get that the W8DBItem object has no associated (and open) connections, but I am not sure how to go about fixing things. I could connect to the DB in the W8DBItem.js file, but I really don't like hard-coding the server info with the objects - I want these objects to be used in different files, and perhaps with different servers.
Ideas and suggestions are much appreciated!
[EDIT: SOLUTION FOUND!!!]
Instead of exporting my mongoose.model from my object file, I am only exporting the schema:
var mongoose = require('mongoose');
var itemSchema = new mongoose.Schema({name: {type: String, required: true}});
module.exports = itemSchema;
In my program files I then do this:
var itemSchema = require('../w8/W8DBItemSchema.js');
...
var W8DBItem = db.model('W8DBItem', itemSchema);
var newWeightItem = W8DBItem(aWeight);
...
Works like a charm. I hope this helps someone!
The posted answer does not solve the problem. Unfortunately, I cannot just upgrade my database, so that is not a solution either for me. But here I found a solution to this problem: https://github.com/Automattic/mongoose/issues/4064
Just use .$__save instead of .save as shown:
var b = new BookModel({title : 'aaaaaa'});
b.$__save({}, function(e){
if(e){
console.log('error')
// callback will show if e exists
}else{
console.log('no error')
// callback will show 'no error'
}});
I am getting start with mongodb and mongoose but am having problems querying a database. There are a number of tutorials online for what I am trying to do but it just doesn't seem to work for me. My problem is that the .find() function is not even being called and the collection is not being displayed. I have a collection called Subjects in which I know there are some values (I manually entered them in the mongodb command line). I only tried including pertinent code but let me know if anything else is needed. Thanks in advance.
app.js file
require('./models/model.js');
var conn = mongoose.createConnection('mongodb://localhost/test');
var Subject = mongoose.model('Subjects');
Subject.find( { }, function (err, subjects) {
if(err) console.log("Error"); // There is no "Error"
console.log("Made it"); // There is no "Made it"
console.log(subjects);
});
model.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectsSchema = new Schema ({
subject: { type: String }
});
module.exports = mongoose.model('Subjects', SubjectsSchema);
Call mongoose.connect instead of mongoose.createConnnection to open the default connection pool that will be used by models created using mongoose.model:
mongoose.connect('mongodb://localhost/test');