I have two schema in singel schema.js file
var mongoose = require('mongoose');
var user = new mongoose.Schema({
name: String,
add: String,
role: String
});
var Organizationn = new mongoose.Schema({
name: String,
add: String,
name:String
});
module.exports = {
user: user,
Organizationn: Organizationn
};
accessing it like
var models = require("../models/schema");
models.user.findOne()
it says findone is not a function
whereas If i use singel user in a file it is working.
I have gone through this link and did export like above
cant get data from database after multiple schema declared (mongoose + express + mongodb
but not working
any idea?
Thanks
With the help of #anthony I figure out the issue
I need to do the below
module.exports = {
user: mongoose.model('user', user),,
Organizationn: mongoose.model('Organizationn', Organizationn)
};
If you exports more than one file than you will have to import with curly braces { schema1 }
var mongoose = require('mongoose');
var user = new mongoose.Schema({
name: String,
add: String,
role: String
});
var organization = new mongoose.Schema({
name: String,
add: String,
name:String
});
const userSchema = mongoose.model('users', user),
const organizationSchema = mongoose.model('organizations', organization)
module.exports = { User: userSchema, Organization: organizationSchema }
and then import
var { User } = require("../models/schema");
var { Organization } = require("../models/schema");
User.findOne()
Organization.findOne()
Try to look at it in this abstract way:
A mongoose.Schema is basically just an object.
A mongoose.model is a class that you customize with your schema object.
In other words, mongoose.model has all the database functions attached to it, the schema by itself doesn't.
Related
so I have two schemas, User und Company
const UserSchema = new mongoose.Schema({
_createdAt: Date,
company: {type: mongoose.Schema.Types.ObjectId, ref: 'company'},
email: String,
});
const CompanySchema = new mongoose.Schema({
_createdAt: {
type: Date,
required: true
},
name: {
type: String,
required: true
}
});
const userModel = mongoose.model("user", UserSchema, "user");
const companyModel = mongoose.model("company", CompanySchema, "company");
I would now like to query for a specific User by his Company _id, but for some reason this is not working, it returns an empty array even though I have a user with the exact company ObjectId in my Database.
userModel.find({company: "5cfa4352ffc1c8135d8276a4"})
.exec((err, user) => {
console.log(user);
}
In my mongo shell the command
db.user.find({company: "5cfa4352ffc1c8135d8276a4"})
returns the users as expected so why does this not work in mongoose? Thanks in advance
Try this
const ObjectId = require('mongodb').ObjectID;
then
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
I hope it will work
If you want to find by that id you probably need to do this:
const mongojs = require('mongojs');
const ObjectId = mongojs.ObjectId;
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
Since you are using moongose, you can get the ObjectId like this:
const mongoose = require('mongoose');
const objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa')
So this is how my models are:
groupModel.js
var Schema = mongoose.Schema;
var groupSchema = new Schema({
uuid: String,
users: [{type: Schema.Types.ObjectId, ref:'users'}]
});
var Groups = mongoose.model('groups', groupSchema);
module.exports = Groups;
userModel.js
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
email: String,
emailVerified: Boolean
});
var Users = mongoose.model('users', userSchema);
module.exports = Users;
and this is the api I am hoping to get it to work:
/* GET /group/list/:id listing. */
router.get('/list/:id', function(req, res) {
Group.findOne({uuid :
req.params.id}).populate('Users').exec(function(err, group){
if(err) throw err;
console.log(group);
res.status(200).send(group);
});
});
this is the response I get back:
{"_id":"5aaf52b4165e97aae4a0b42c","uuid":"iyzIc","__v":0,"users":
["58f5acae4733ae5f64XXXXea","590a663c2a32ad28e0XXXX29"]}
For some reason I am not able to replace the id's with actual data for the users. I was hoping to get user related details instead of ids for the two users. Am I doing something wrong? I am trying to learn nodejs and was hoping some nodejs expert will be able to find my silly mistake.
EDITED:
changing .populate('Users') -> .populate('users') fixed the issue.
Users being capitalized in populate is the problem!
I've this:
models/record.js
var mongoose = require("mongoose");
var RecordSchema = new mongoose.Schema({
address : require("./address").Address
});
var Record = mongoose.model('Record', RecordSchema);
module.exports = {
Record: Record
}
models/address.js
var mongoose = require("mongoose");
var AddressSchema = new mongoose.Schema(
{
streetLine1: String,
streetLine2: String,
city: String,
stateOrCounty: String,
postCode: String,
country: require("./country").Country
});
var Address = mongoose.model('Address', AddressSchema);
module.exports = {
Address: Address
}
models/country.js
var mongoose = require("mongoose");
var CountrySchema = new mongoose.Schema({
name: String,
areaCode: Number
});
var Country = mongoose.model('Country', CountrySchema);
module.exports = {
Country: Country
}
It's actually showing this error:
TypeError: Undefined type Model at country
Did you try nesting Schemas? You can only nest using refs or arrays.
I am trying to create a model where few types is another model. How to archive this ?
The problem here is that you are exporting a model from country.js and using the same by requiring in the address schema creation. While creating nested schemas, the value for a property should be a schema Object and not a model.
Change your country.js to:
var mongoose = require("mongoose");
var CountrySchema = new mongoose.Schema({
name: String,
areaCode: Number
});
module.exports = {
Country: CountrySchema
}
I need to read a collection identified connected to a mongoose model. Is the correct approach to read the property model.schema.options.collection directly or is there any more suitable approach?
As far as i have understood, you want to use the property of your mongoose schema. i will provide you with a small example to how you can use it effectively.
Your model file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//Schema for User
var UserSchema = new Schema({
name: {
type: String,
},
email: {
type: String
},
password: {
type: String,
},
});
module.exports = mongoose.model('User', UserSchema);
In your function where you want to include this model
var User = require('/path/models/user');
var UserController = {
create: function(req, res){
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
//rest of the functionality on these bod params.
}
}
I hope this small example will be able to help.
What is the best way to require a mongoose Schema in nodejs?
Originally I had these inside the app.js file but that is getting a bit large and unwieldy with more models.
Now I want to move them into a models folder and use Model = require('./models/model') to import them into app.js
How do I get it such that Model is populated with the actual model?
(exports = mongoose.model(...) fails and gives me a blank object; exports.model = mongoose.model(...) requires me to do Model.model to access it -- neither of these are the desired behavior)
===
Edit1
So basically I have taken
var mongoose = require('mongoose');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var UserSchema = new Schema({
username: String,
password: String,
first_name: String,
last_name: String,
email: String
});
User = mongoose.model('User', UserSchema);
and put it into ./models/user.js
How do I get it such that its the equivalent of having this in the app.js?
In your app.js server file, include the model.js file like this:
var Model = require('./models/model'); //whatever you want to call it
You can then instantiate it in your server file like this:
//Initiate the Business API endpoints
var model = new Model(mq, siteConf);
model.getUser(id, function() {
// handle result
});
----
Then in your file you place in models folder named model.js (or whatever you want) you can set it up like this:
var mongoose = require('mongoose');
//MongoDB schemas
var Schema = mongoose.Schema;
var User = new Schema({
username: String,
password: String,
first_name: String,
last_name: String,
email: String
});
var UserModel = mongoose.model('User', User);
// your other objects defined ...
module.exports = function(mq, siteConf) {
//MongoDB
mongoose.connect(siteConf.mongoDbUrl);
// ------------------------
// READ API
// ------------------------
// Returns a user by ID
function getUser(id, found) {
console.log("find user by id: " + id);
UserModel.findById(id, found);
}
// Returns one user matching the given criteria
// mainly used to match against email/login during login
function getUserByCriteria(criteria, found) {
console.log("find user by criteria: " + JSON.stringify(criteria));
UserModel.findOne(criteria, found);
}
// more functions for your app ...
return {
'getUser': getUser,
'getUserByCriteria': getUserByCriteria
};
};