I'm new to CompoundJS. I'm working on a sample app. If following the below tutorial:
Using Mongoose Models
I have written the below code in db/schema.js file:
customSchema(function () {
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
module.exports["mongoose"] = mongoose;
module.exports["model"] = {}
});
In my model.js file (person.js), I have the code below:
var Person = mongoose.model('Person', new module.schema());
model['Person'] = Person;
When I run compound s , I'm getting ReferenceError: mongoose is not defined.
Any help would be appreciable. Thanks in advance.
Wiki is outdated, all documentation currently available at http://compoundjs.com, and i will remove wiki to avoid confusions.
You can use this example if you need mongoose as ORM: https://github.com/anatoliychakkaev/mongoose-compound-example-app
Related
It seems pretty clear that defining a model in one file but using it in another is common practice. I don't know why I'm having so much trouble getting it to work. I spent the morning rewriting my simple MongoDB app to follow what I thought was a dead simple example. I'm just structuring it like the top answer with the added convenience that the file where I define the Schema and Model and access the Model are in the same folder (because the project is so small and I'm just learning MongoDB). I think part of the problem as I tried researching solutions is that other examples really complex to follow. The DB connects as expected and I can work in the ManageDB.js file fine, but of course want to keep the project organized, even at my small scale. (The server.js file in the directory above connects before this code executes.)
What other things can I try to troubleshoot this MongoDB application?
// src/ManageDB.js
const mongoose = require('mongoose');
const devTweetRecordsModel = new mongoose.Schema({
time: Date,
text: String,
source: String,
positive: Number,
negative: Number,
});
var tweetdb = mongoose.model('DevTweetDB', devTweetRecordsModel);
module.exports = {
tweetdb: tweetdb
};
// src/TwitterAPI.js
const mongoose = require('mongoose');
var tweetdb = require('../src/ManageDB').tweetdb;
console.log(tweetdb); // Returns undefined
After defining a model-schema in mongoose you should assign it as mongoose.model
as you can see in the documentation.
https://mongoosejs.com/docs/models.html
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
When you call mongoose.model() on a schema, Mongoose compiles a model for you.
and then you can use it by requiring it in another file.
const Model= require('./../models/modelName');
I solved it a way I hadn't seen suggested anywhere so I will post here for completeness. The solution was very sensitivity to how I exported it and brought it into the other JS file.
// Model.js
module.exports = mongoose.model('DevTweetDB', devTweetRecordsModel);
// TwitterAPI.js
var tweetdb = require('../models/tweetdb');
console.log(tweetdb);
// Returns the object as expected:
// Model { DevTweetDB }
I'm pulling my hair out.
I've tried using mongoose:
const ObjectId = require('mongoose').Types.ObjectId;
let id = new ObjectId(peson["_id"]);
When I console.log(id) it just shows the string value.
When I append the id into an array in another object I'm using, and I JSON.stringify() that whole
object I get just the '1djd892jowidj3wfejk93' string values.
When I pass my searchObject to Mongo, it doesn't return results.
I've also tried using the native MongoDB driver for node:
const {ObjectId} = require('mongodb');
let id = Objectid("1djd892jowidj3wfejk93")
this also returns just a string value when when logging to the console and also embedding in parent search request. JSON.stringify() shows just the string, and the query returns empty.
the native NodeJs mongoDb driver
Try the following:
const {ObjectID} = require('mongodb');
const id = new ObjectID('5e059042b091f6000a4bf236');
Try this
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('1djd892jowidj3wfejk93');
You don't need to use extra dependency if you are using mongoose,
const mongoose = require('mongoose');
function convertToObjectID(id) {
return mongoose.Types.ObjectId(id)
}
How can we access data from two different databases, on a same page using MEAN-stack? For example I want to give user Information and user watch history(both are different databases) on same page?
you could just create multiple files for your separate mongoose connections.
for example in db_one.js:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db_one');
module.exports = mongoose;
and then in db_two.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db_two');
module.exports = mongoose;
and then import them in other Files as you wish
Disclaimer:
I am new to mongoose/node, so please excuse me if I am misunderstanding some basic things.
Yes, I found already a few postings about this topic, but could not adapt it to my needs.
I structured my main-project into multiple separate projects. One separation is the "app-core" project, which will contain the core-models and -modules, to be injected by each other project (app-core is configured as dependency in the package.json file of each project).
A (simplified) model within the app-core currently looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var IndustrySchema = new Schema({
name: {
type: String,
required: true
}
});
module.exports = mongoose.model('Industry', IndustrySchema);
The wep-app includes this model as follow:
var Industry = require('app-core/models/Industry');
and creates the MongoDB connection like this:
var DB_URL = 'mongodb://localhost/hellowins';
var mongoose = require('mongoose');
var mongooseClient = mongoose.connect(DB_URL);
mongooseClient.connection.on('connected',function () {
console.log("MongoDB is connected");
});
Now I have the problem, that the model will not use the mongo connection that is defined in the app-web project, rather it will consider the connection configured in the app-core.
Due to encapsulation and responsibility design I definitly don't want the core to define the connections for each possible app (which may include the core-app).
So somehow I need to specify the the scheme only in the core.
I read already that I should not require the model itself (/app-core/models/Industry), and use the mongoose model instead
var Industry = mongoose.model("Industry");
But then I get the error
MissingSchemaError: Schema hasn't been registered for model "Test"
To fix this, I should register the models manually, like adviced in the first link (at the top of my posting). But somehow I don't like this approach, because I'd need to extend this everytime the application uses a new model.
And further I need a mongo connection even in the core-app - at least to run the mocha tests.
So I am bit confused about how to structure the architecture in this case.
UPDATE #1
I found now one working solution. But, unfortunately, this does not fit my requirements completely, because it is pretty difficult (resp. ugly) to extend a model by hooks (ie TestSchema.pre('save'..)).
Model (app-core)
exports.model = {
name: {
type: String,
required: true
}
};
models.js (app-web, executed once on startup)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var models = ['Test']; // add many
exports.initialize = function() {
var l = models.length;
for (var i = 0; i < l; i++) {
var model = require('hw-core/models/' + models[i]);
var ModelSchema = new Schema(model.model);
module.exports = mongoose.model(models[i], ModelSchema);
}
};
app.js (web-app)
require('./conf/app_models.js').initialize();
Then I just can get a model as follow
var mongoose = require('mongoose');
var TestModel = mongoose.model("Test");
var Test = new TestModel();
Why don't you try to export the mongoose instance from your app-core module and use it later in the web-app to connect to a database
app-core index.js
var mongoose = require('mongoose');
module.exports = {
mongooseInstance: mongoose };
web-app index.js
var core = require('app-core'),
mongoose = core.mongooseInstance,
mongooseClient = mongoose.connect(DB_URL);
// and so on
This might work as long as you require your models in your controllers which are initialized after the code from the index.js. I hope my response is helpful.
I'm using Mongoosejs, with MongoDB and Node.js.
I followed some online tutorials and created myself a test app as below, but keep getting the error message "propert model of object mongoose is not a function.
I dont understand what this means and why its erroring since i followed the online tutorials near enough the same.
Here is my code
// MongoDB test app. Getting to know MongoDB via MongooseJS
var mongoose = require ('mongoose'),
Schema = mongoose.Schema;
//Create Schema
var Storydb = new Schema ({
title: String,
body: String,
date: Date
});
mongoose.connect('mongodb://localhost/test');
//setup model and pass it schema
mongoose.model = ('Storydb',Storydb);
var StoryModel = mongoose.model ('Storydb');
var story = new StoryModel();
//Insert Data
story.title = 'The Man in the green shirt';
story.body = 'once upon a time, way back';
story.date = Date.now();
//save
story.save(function(err){
if (err) {throw err; }
console.log('saved story');
mongoose.disconnect();
});`
I've already tested my MongoDB connection. No issues there, and i am able to insert and retrieve data via the Mongo CLI.
I have also tested my Node.js configuration with basic Hello World examples, and no issues with configuration.
Instead of:
//setup model and pass it schema
mongoose.model = ('Storydb',Storydb);
you should do:
//setup model and pass it schema
mongoose.model('Storydb',Storydb);