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?
Related
i came across this error today and did not find a fix for it.
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
name: {type:String, required:false},
birthday: {type:String, required:false},
email: {type:String, required:false},
hobbies: {type:String, required:false},
picture: {type:String, required:false},
});
const User = mongoose.model("User",userSchema);
module.exports = User;
If you hover over Schema it will show the error : "Method expression is not of Function type"
I later use this Schema here:
const User = require("../models/user");
exports.createUser = (req, res, next) => {
const url = req.protocol + "://" + req.get("host");
const user = new User({
name: req.body.name,
birthday: req.body.birthday,
email: req.body.email,
hobbies: req.body.hobbies,
picture: req.body.picture
});
console.log(user);
user
.save()
.then((createdUser) => {
console.log(createdUser);
res.status(201).json({
message: "User added successfully",
});
})
.catch((error) => {
res.status(500).json({
message: "Creating user failed!",
});
});
};
The console log of user is the following:
{
name: 'Chris',
birthday: 'test',
email: 'test',
hobbies: 'test',
picture: 'test',
_id: new ObjectId("61c0a908e340bcdec1011de5")
}
The _id should not contain new ObjectId and only the part in the brackets.
I hope you can find a fix for this or an idea on how it should be done.
According to the latest Mongoose docs, if you redo it like so:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const userSchema = new Schema ({
...
});
That should fix it, so you're creating a new instance of a Schema object, rather than calling a Schema "method".
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.
I'm using mongoose (last version , fresh install) for a MEAN architecture (mongo+express+angular+nodejs) and i'm approaching to save some data into my mongodb.
I have a db called "cogestione" and three collections: "ragazzi", "sedi" and "corsi".
I want to save a data of type Ragazzo in collection "ragazzi". I connect with:
mongoose.connect("mongodb+srv://admin:************.mongodb.net/cogestione?retryWrites=true", { useNewUrlParser: true })
.then(() => console.log("Connection to database correctly happened"))
.catch((err) => console.log(err))
and all goes smoothly. In another file i have the model:
const mongoose = require("mongoose");
const postSchema = mongoose.Schema(
{
nome: {
type: 'String'
},
cognome: {
type: 'String'
},
classe: {
type: 'String'
},
email: {
type: 'String'
}
}
);
module.exports = mongoose.model("ragazzo" , postSchema);
and i export it with the last line. Then , back in the app i send it to the db with:
const post = new Ragazzo({
nome: req.body.nome,
cognome: req.body.cognome,
classe: req.body.classe,
email: req.body.email
});
console.log(post);
post.save()
.catch((err)=>{console.log(err)});
res.status(201).json({message : "Post added"});
The problem is that it doesn't save my doc into "ragazzi" collection , but it creates a new collection called "ragazzos"... how can i tell mongoose to save it into a fixed collection?
Create your mongoose Schema like as bellow.
const mongoose = require("mongoose");
const postSchema = mongoose.Schema(
{
nome: {
type: 'String'
},
cognome: {
type: 'String'
},
classe: {
type: 'String'
},
email: {
type: 'String'
}
}, {collection: 'ragazzi'});
your problem is you use this line
module.exports = mongoose.model("ragazzo" , postSchema);
but not export the compiled model.. you should export the compiled model like this
const Post = module.exports = mongoose.model("ragazzo" , postSchema);
then in your router import it like so
const post = require("./models/Post"); // in your case keep your file path
const post = new Post({
nome: req.body.nome,
cognome: req.body.cognome,
classe: req.body.classe,
email: req.body.email
});
console.log(post);
post.save()
.catch((err)=>{console.log(err)});
res.status(201).json({message : "Post added"});
this will work the way you want it mate .. cheers
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');