Can't save a document to mongodb with mongoose - node.js

I have my schema as this
var Schema = mongoose.Schema;
var schema = new Schema({
uid : {type: String, required: true},
title: {type: String, required: true},
description: {type: String, required: true}
})
module.exports = mongoose.model('Task', schema)
In another file, I include this file, and try to seed the db:
var Task = require('../models/task');
var uuid4 = require('uuid4')
var mongoose = require('mongoose')
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/app', {useNewUrlParser: true});
var task = new Task({
uid: uuid4(),
title: 'task3 name',
description: 'task3 desc'
})
task.save(function (err) {
if (err) console.log(err)
})
}
No matter what I do, it won't save the data I want.
Now, when I dive into the db, app database, tasks collection, there are no inserts over there
version: "mongoose": "^5.5.2",

According to this documentation
If you create a custom connection, use that connection's model() function instead.
var connection = mongoose.createConnection('mongodb://localhost:27017/test');
var Tank = connection.model('Tank', yourSchema);
So you need to declare your model from your connection so that it knows which connection to associate the .save() action.
I would recommend creating a dedicated db.js file that handles creating the connection which can then be imported into each of your schema files in order to create the model from the supplied connection.

Related

Data seeded with Mongoose not being saved in MongoDB

I'm trying to add some data to MongoDB using Mongoose, but I'm having trouble getting that data to save to my database. I'm following this tutorial on YouTube (~11 min), but I think the video might be using a different version of Mongoose.
Basically, I have a Product schema defined in a separate JS file, and I'm running a file called productSeeder.js by running node productSeeder.js in terminal with the Mongo daemon running. When I switch to the correct database and type db.products.find() into the Mongo shell, nothing is returned to me.
My productSeeder.js file:
var Product = require('../models/product');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopping');
var products = [
new Product({
imagePath: 'images/dummy.png',
price: 9,
title: 'a title',
desc: 'some text'
}),
new Product({
imagePath: 'images/dummy.png',
price: 5,
title: 'a title',
desc: 'some text'
})
];
var done = 0;
for (var i = 0; i < products.length; i++) {
products[i].save(function(err, result) {
if (err) {
console.log(err);
return;
};
done++;
if (done == products.length) {
mongoose.disconnect();
};
});
};
My product.js file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath: {type: String, required: true},
price: {type: Number, required: true},
title: {type: String, required: true},
desc: {type: String, required: true}
});
module.exports = mongoose.model('Product', schema);
Thanks so much, and happy holidays!
Do you know if Mongoose has successfully been connected before you try to save the Products?
One thought could be that since the Db access is async, you're trying to save off items before the connection exists.
You could pass a callback to your connection or use an event listener and wrap your save functions in the connection callback.
mongoose.connection.on('connected', function(){
//save products here
});
I've read of a few cases of Mongoose failing to save without error.
Edit: might be better to listen for .on('open') instead (mongoose docs).

Mongoose populate across 2 databases

I have a node app that uses 2 databases. One is the the Names and the other for the rest of all the data.
I have this connection setup:
// DATABASE CONNECTION
var APP_DB_URI = config.APP_DB; // mongodb://localhost:27017/app_db
var app_DB = mongoose.createConnection(APP_DB_URI);
var name_DB = app_DB.useDb(config.NAME_DB); // 'name_db'
This connection is working properly.
There's also no problem upon saving data to both app_db and names_db working perfect.
But the problem is this: when I try to query let say the Account model and then populate the referenced Name model, the populate process returns null.
Account schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var field = {
email: {type: String, unique: true},
password: {type: String, select: false},
name: {type: Schema.Types.ObjectId, ref: 'Name'},
}
var options = {
id: false,
versionKey: false
}
var schema = new Schema(field, options);
module.exports = mongoose.model('Account', schema);
Name schema:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var field = {
firstName: {type: String, required: true},
middleName: {type: String, required: true},
lastName: {type: String, required: true},
suffix: {type: String, required: false,},
}
var options = {
id: false,
versionKey: false
}
var schema = new Schema(field, options);
module.exports = mongoose.model('Name', schema);
The query and population:
var app_db = *app_db instance passed to this controller*
var Account = app_db.model('Account');
Account.findOne({email:req.body.email})
.populate('name')
.exec(function (err, user) {
if(user){
// user.name returns null
}
})
Is there a special way to populate data from db1 the data from db2? Thanks.
Populate Mongo documents across databases feature added since mongoose v3.9.0. Per this across db populate test, you should different db name when model is called. Some sample codes as below. More details please refer to the test codes in the link.
var app_DB = mongoose.createConnection(APP_DB_URI);
var name_DB = app_DB.useDb(config.NAME_DB); // 'name_db'
// ...
module.exports = app_DB.model('Account', schema);
// ...
module.exports = name_DB.model('Name', schema);
Populate
.populate('name', '', Name)

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.

Saving Mongoose object into two collections

Currently I have a node application which uses mongoose to save an object into a MongoDB. I am using a model similar to this:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var RegistrationSchema = new Schema({
name:{ type: String, default: '', trim: false}
});
mongoose.model('Registration', RegistrationSchema);
Which saves my objects into a collection called registrations.
I save my registrations as such:
var registration = new Registration(data);
registration.save(function(err) {
if (err) {
return callback({
source: 'data_save',
type: 'admin',
errors: err
});
}
else {
return callback(null, data);
}
});
I would also like to save this same object when I create it, into another collection with a different name, such as registrations_new, or something to that effect. I want to duplicate this entry into the new collection. I tried to add the other collection in the connection string, which broke the mongo part entirely, I tried to create a new model called New_Registration, load that Schema and try to save it individually, but I have another issue with that. It seems that Mongoose pairs the schema with the collection, and that there really is no way to overwrite which collection it is saving to.
Anyone have any solution for this?
You can use the same schema in multiple models, so something like this works:
var RegistrationSchema = new Schema({
name:{ type: String, default: '', trim: false}
});
var Registration = mongoose.model('Registration', RegistrationSchema);
var New_Registration = mongoose.model('New_Registration', RegistrationSchema);
var registration = new Registration(data);
registration.save();
var new_registration = new New_Registration(data);
new_registration.save();

Closing DB in Mongoose

I have the following code to insert record in Mongo by using Mongoose.
var mongoose = require('mongoose');
var config = require ('config');
var db = mongoose.createConnection(config.database.address, config.database.dbName);
var strCollectionName = 'category';
var CategorySchema = new mongoose.Schema({
categoryName : {type: String, required: true , unique: true },
categoryTag : {type: String},
categoryDescription : {type: String},
createDate : {type: Date, default: Date.now}
});
var createCategory = function (objCategory)
{
var Category = db.model(strCollectionName, CategorySchema );
var objSchema = new Category(objCategory);
objSchema.save(function (err)
{
if (err)
console.log ("Error");
else
console.log ("Success !!");
});
}
I managed to make it work. But if i try to issue db.close () command inside save it throws error otherwise it is good. My questions is I should not have to close the connection at all ? Will Mongoose automatically takes care it ? - Im worried if the connection pool goes beyond the limit then the entire DB might crash.
To do this properly:
Define your models and tell Mongoose about them at the same time. You can do this before you create the connection.
You were previously telling Mongoose about your schema right when you wanted to use it - you only need to do this once, when you create the schema itself.
You can then open a connection for Mongoose which will work across your whole application (i.e. to use it subsequently, you just have to require('mongoose')):
var mongoose = require('mongoose');
var config = require ('config');
var CategorySchema = new mongoose.Schema({
categoryName : {type: String, required: true , unique: true },
categoryTag : {type: String},
categoryDescription : {type: String},
createDate : {type: Date, default: Date.now}
});
mongoose.model('Category', CategorySchema);
mongoose.connect(config.database.address, config.database.dbName);
If you want to manually create and manage connections you can, using .createConnection as in your example above, but unless you know what you're doing it's better to just use Mongoose's default connection.
To create a category:
// if you're in a different file to where you created your CategorySchema, var these:
var mongoose = require('mongoose'),
Category = mongoose.model("Category");
var createCategory = function (objCategory) {
var newCategory = new Category(objCategory);
newCategory.save(function (err) {
if (err)
console.log ("Error");
else
console.log ("Success !!");
});
}

Resources