I try to create a dedicated mongoose createConnection. Node.js rapports:
MyModel = conn.model('Profile', profileSchema),
profileSchema is not defined. But where did I go wrong?
//my db.js
const mongoose = require('mongoose');
const conn = mongoose.createConnection = ("mongodb://localhost:27017/myDatabase"),
MyModel = conn.model('Profile', profileSchema),
m = new MyModel;
m.save(); //works;
if (process.env.NODE_ENV === 'production') {
conn = process.env.MONGODB_URI;
}
require('./profiles)
Here the rest of my model page:
// my profile.js
// JavaScript source code
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
var MyModel = mongoose.model('Profile', profileSchema);
What you have to do is
// my profile.js
// JavaScript source code
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
module.exports = mongoose.model('Profile', profileSchema);
and in your app.js file put like this
const profileInfo= require('./../model/profile.js');
There are many issues with your code, First learn how module works in javascript.
You need to export the profileSchema inorder to use inside the app.js, it should be,
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
module.exports = mongoose.model('Profile', profileSchema);
then need to import profileSchema which lies inside profile depend on your file path.
const profileSchema = require('./model/profile.js');
Related
I have defined these three models in mongoose:
const clientSchema = new mongoose.Schema({
name: String,
role: String,
age: {
type: Number,
default: 10
}
})
clientSchema.pre('save', function(){
const doc = this
doc.role = 'client'
})
const adminSchema = new mongoose.Schema({
name: String,
role: String,
})
adminSchema.pre('save', function(){
const doc = this
doc.role = 'admin'
})
const userSchema = new mongoose.Schema({
name: String,
role: String,
age: {
type: Number,
default: 10
},
})
const AdminModel = mongoose.model('AdminModel', AdminModel, 'users')
const ClientModel = mongoose.model('ClientModel', ClientModel, 'users')
const UserModel = mongoose.model('UserModel', UserModel, 'users')
and I have the following route in my express app:
app.route('/users').get(async(req, res, next)=>{
const docs = UserModel.find({ role: 'admin' })
})
It works as expected, except that it's returning the following to the client-side:
{
"name": "James Breakers",
"role": "admin",
"age": 10
}
and this is wrong, and it causes many problems.
On write, it works great, it saves it in the database without the age: 10, but the problem is when retrieving (reading) from the database, Mongoose is setting the field age: 10.
and All of that is only because I used the UserModel to retrieve that admin. But I don't want that default behavior of Mongoose at all.
How can I disable it? is there a schema option for that?
I'm using Passport Local Mongoose to create a user on my database. My goal is to allow users with the same username to register into my app. On my research, i found that if i pass an object as option on my Schema.plugin with 'usernameUnique: false', i would allowed users to register with the same username. The only problem is when a try it to make a register, i get an "UserExistsError" on my console.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const UserSchema = new Schema({
email: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: false
},
});
const options = {
usernameUnique: false,
}
UserSchema.plugin(passportLocalMongoose, options);
const User = mongoose.model('User', UserSchema);
module.exports = User;
this is my code in routes/blog.js
var express = require('express');
var router = express.Router();
const Blogs = require("../models/blog");
and this my code in models/blog.js
const mongoose = require('mongoose');
const mongo = require('mongodb');
const dbUrl = 'mongodb://localhost:27017/BlogDB';
mongoose.connect(dbUrl, { useNewUrlParser: true });
const db = mongoose.connection;
const Schema = mongoose.Schema;
const blogSchema = new Schema({
id: {
type: Schema.ObjectId
},
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
category: {
type: String,
required: true
},
content: {
type: String,
required: true
},
})
const Blogs = module.exports = mongoose.model("blogs", blogSchema);
//module.exports = mongoose.model("blogs", blogSchema);
I've tried some basic solutions. But still can't use npm start ,
Is there any way I can get it to work? I'm a beginner, please.
In your routes/blog.js edit 3rd line to this const Blogs = require("../views/models/blog"); should resolve your problem.
I am trying to import a schema file(order.js) inside user.js from "models" folder.
My application gets crashed after saving user.js, it throws an error as follows,
"TypeError: Invalid value for schema path product.type, got value "undefined""
In user.js, I have imported order.js as follows,
const User = require("../models/user");
const Order = require("../models/order"); //Throws error on this line.
But when I comment require("../models/order") line, app starts to perform well.
This is my multiple Schema file (order.js):
const mongoose = require("mongoose");
const { Objectid } = mongoose.Schema;
const productCartSchema = new mongoose.Schema({
product: {
type: Objectid,
ref: "Product",
},
name: String,
count: Number,
price: Number,
});
const ProductCart = mongoose.model("ProductCart", productCartSchema);
const orderSchema = new mongoose.Schema(
{
products: [productCartSchema],
transactionid: {},
address: String,
amount: { type: Number },
updated: Date,
user: {
type: Objectid,
ref: "User",
},
},
{ timestamps: true }
);
const Order = mongoose.model("Order", orderSchema);
module.exports = { Order, ProductCart };
I have found a solution on this issue.
The ObjectId in my order.js is not defined. I just replaced it with mongoose.Schema.Types.ObjectId
This solved my issue.
so my question is how can i display data of a model that has an attribute reference to another model? In this task i have Driver model that has attribute state which should reference another model called State that has a name attribute. I know hot to reference models in mongoose but i don't know how to build API for creating new Driver and displaying it.
Below is my Driver and State models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Driver = new Schema({
name: {
type: String
},
phone: {
type: String
},
email: {
type: String
},
deleted: {
type: Boolean
},
state: {
type: Schema.ObjectId,
Ref: 'State'
}
});
module.exports = mongoose.model('Driver', Driver);
This is model of State
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let State = new Schema({
name: {
type: String
}
});
module.exports = mongoose.model('State', State);
Currently my API are looking like this
driverRoutes.route('/').get(function(req, res){
Driver.find(function(err, drivers){
if(err){
console.log("Error");
} else {
res.json(drivers);
}
});
});
driverRoutes.route('/:id').get(function(req, res){
let id = req.params.id;
Driver.findById(id, function(err, temp){
res.json(temp);
});
});
driverRoutes.route('/add').post(function(req, res){
let temp = new Driver(req.body);
temp.save()
.then(temp =>{
console.log(temp.state);
res.status(200).json({'driver': 'driver added successfully'});
})
.catch(err => {
res.status(400).send('adding new driver failed');
});
});
Route with / is to display all Drivers in table.
Change your Driver model to look as below,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Driver = new Schema({
_id: {
type:Schema.Types.ObjectId
},
name: {
type: String
},
phone: {
type: String
},
email: {
type: String
},
deleted: {
type: Boolean
},
state: {
type: Schema.Types.ObjectId, //this is the change made
Ref: 'State'
}
});
module.exports = mongoose.model('Driver', Driver);
The second step is optional. That is, in your state model,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let State = new Schema({
_id:{
type:Schema.Types.ObjectId //this is optional however
},
name: {
type: String
}
});
module.exports = mongoose.model('State', State);
That should help.