I have a couple models that are in going to be held in separate files and I can't seem to find a way to reference them without resorting to having them in the same file.
My first file contains the following:
var mongoose = require('mongoose'),
bcrypt = require('bcrypt'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true,
trim: true,
required: true
},
hash_password: {
type: String
},
/* etc */
});
UserSchema.methods.comparePassword = function(password) {
return bcrypt.compareSync(password, this.hash_password);
};
module.exports = mongoose.model('User', UserSchema);
And the second file is this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ThreadSchema = new Schema({
title: {
type: String,
required: true,
trim: true
},
created_by: {
type: { type: Schema.Types.ObjectId, ref: 'User' },
required: true
}
/* etc */
});
module.exports = mongoose.model('Threads', ThreadSchema);
I keep getting this error: "TypeError: Undefined type undefined at created_by.required". The code works if I keep the user and thread models in the same file but when I separate the files, they no longer can reference each other. I tried adding require('./userModel') at the top of the threadModel but that didn't work either.
Any help is appreciated.
Related
I have created two models where I am trying to ref one model to another but it's not working and I don't have any idea about it I used it exactly the same way as in the mongoose example but it is not helping, the only difference between my working and their example is I have two different files for both models and I am exporting them to use in another file
The example I took reference from Mongoose
First Model
const userModel = require('./userModel')
const {Schema} = mongoose
const tweet = new Schema({
date: {
type: Date,
required: true,
},
msg:{
type: String,
maxlength:140,
required:true
},
tweetid:{
type: mongoose.Types.ObjectId
}
})
const tweetSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'userModel'
},
tweets: {
type: [{tweet}],
default: []
}
})
const tweetModel = mongoose.model('tweet',tweetSchema)
module.exports = tweetModel
Second Model
const {Schema} = mongoose
const userSchema = new Schema({
email: {
type:String,
required: true,
unique: true,
trim:true
},
password: {
type:String,
required: true,
trim:true
},
follows: {
type: [String],
default: []
}
})
const userModel = mongoose.model("User",userSchema)
module.exports = userModel
Your reference string should be equal to the model name that you have passed to mongoose.model:
const tweetSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
tweets: {
type: [{tweet}],
default: []
}
})
i was searching internet for 2 days now and did not find any answer,
const mongoose = require('mongoose');
const channelsSchema = new mongoose.Schema(
{
stateName: {
type: String,
required: [true, 'A state must have a name'],
unique: true,
index:true
},
id: {
type:String
},
Name: {
type:String
},
**anyThing: [Object]
},
{ strict: false }
);
const Channels = mongoose.model('Channels', channelsSchema);
module.exports = Channels;
is there any way to **anything accept anything?
note: its not a big project and im not worried about the security. it runs only localy
You can pass {strict: false} as second argument to the Schema to achieve this.
const mongoose = require('mongoose');
const channelsSchema = new mongoose.Schema({}, {strict: false})
const Channels = mongoose.model('Channels', channelsSchema);
module.exports = Channels;
I have two schemas, a "projects" schema, and an "applications" schema.
What is the most efficient way of creating a new entry in a collection and updating an existing entry in another collection based on data inside the new entry? Can I avoid making multiple API requests and somehow run a "stored procedure" on the mongoDB end to handle updating the Projects collection when there is a change in the Applications collection?
In this scenario, ideally when an application for a project is created, a new entry is created in the Applications collection and the Project in the Projects collection is updated to reflect the information in the Application.
Can I do this without making multiple api requests?
Project Schema:
// models product.js
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;
const projectSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
maxlength: 32
},
applications: {
type: Number,
default: 0
},
created_by: {
type: ObjectId,
ref: 'User'
},
applicants: {
type: Array,
default: []
}
}, {timestamps: true}
);
module.exports = mongoose.model("Project", projectSchema);
Application Schema:
const mongoose = require('mongoose');
const applicationSchema = new mongoose.Schema({
applicantId: {
type: ObjectId,
ref: 'User'
},
ownerId: {
type: ObjectId,
ref: 'User'
},
projectId: {
type: ObjectId,
ref: 'Project'
}
}, {timestamps: true});
module.exports = mongoose.model("Application", applicationSchema);
Note that these are separate schemas because they each carry around 15 fields, i've trimmed them down to post this question.
I suggest to use hooks for mongoose model, there is a post save hook which you can use on Application model to update Project and increment application count.
EDIT - Added Pseudo Code
Project Model
// models -> project.js
const mongoose = require('mongoose');
const {
ObjectId
} = mongoose.Schema;
const projectSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
maxlength: 32
},
applications: {
type: Number,
default: 0
},
created_by: {
type: ObjectId,
ref: 'User'
},
applicants: {
type: Array,
default: []
}
}, {
timestamps: true
});
projectSchema.statics = {
/**
* Find project by _id
*
* #param {ObjectId} _id
* #api private
*/
get: function (_id) {
return this.findOne({
_id
})
.exec();
}
}
module.exports = mongoose.model("Project", projectSchema);
Application Model
const mongoose = require('mongoose');
const projectModel = require("./project")
const applicationSchema = new mongoose.Schema({
applicantId: {
type: ObjectId,
ref: 'User'
},
ownerId: {
type: ObjectId,
ref: 'User'
},
projectId: {
type: ObjectId,
ref: 'Project'
}
}, {
timestamps: true
});
// Async hook
applicationSchema.post('save', function (doc, next) {
const relatedProject = projectModel.get(doc.projectId);
relatedProject.applications++;
relatedProject.save();
next();
});
module.exports = mongoose.model("Application", applicationSchema);
I`m trying create ref from one collection to another collection but not with ref on id.
For example: I have two schema, user and foo. Foo has one unique property 'name'.
USER
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
username: {
type: String,
require: true
},
foo: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Foo'
}
});
mongoose.model('User', userSchema);
FOO
const mongoose = require('mongoose');
const fooSchema = mongoose.Schema({
name: {
type: String,
require: true,
index: {
unique: true
}
}
});
mongoose.model('Foo', fooSchema);
This is work perfect, but can I do ref on that unique property (not on _id)? Like this:
const userSchema = mongoose.Schema({
username: {
type: String,
require: true
},
foo: {
type: String,
property: 'name',
ref: 'Foo'
}
});
Thanks for any answers ;)
I've the following mongoose schema:
'use strict';
const PostSchema = new Schema({
description: require('../fields/description'),
image: require('../fields/image'),
createdAt: require('../fields/createdAt'),
location: Location,
owner: require('../fields/owner') }, {
toObject: {
virtuals: true,
getters: true,
setters: true
},
toJSON: {
virtuals: true,
getters: true,
setters: true
} });
module.exports = mongoose.model('Post', PostSchema);
LocationSchema.js
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const LocationSchema = new Schema({
description: {
type: String,
required: true
},
point:{
type: [Number],
index: '2d',
required: true
},
createdAt:{
type: Date,
required: true,
default: new Date()
}
});
module.exports = mongoose.model('Location', LocationSchema);
and when i will restart my nodejs server i've the following error message:
TypeError: Undefined type Model at location Did you try nesting
Schemas? You can only nest using refs or arrays.
Someone know how to solve this ?
your error here represents that you have not given reference to location key in your post collection if you want to give location id to your post collection you have to provide reference to your collection.
example:
var PostSchema = new mongoose.Schema({
location: [{ type: mongoose.Schema.Types.ObjectId, ref: 'location' }]
});