missing values when saving model - mongodb

When storing a new UserModel all that saves is
{ _id: 5d9e1ddf27c26e4aec7d3d20, __v: 0 }
Here is the Schema
const mongoose = require('../../db/index');
const bcrypt = require('bcryptjs');
const Schema = mongoose.Schema;
const OrganisationModel = require('../../models/organisations/index');
function hash(val) {
'use strict';
if (typeof val !== 'string') {
val = '';
}
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(val, salt);
return hash;
}
const UserSchema = new Schema({
forename: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
password: {
type: String,
required: true,
set: hash
},
email: {
type: String,
required: true,
unique: true
},
organisation: {
type: Schema.Types.ObjectId,
ref: OrganisationModel,
required: true
},
date: {
type: Date,
default: Date.now()
}
});
module.exports = UserSchema;
Here is the model
const mongoose = require('../../db/index');
const UserSchema = require('../../models/users/index');
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;
And here is the saving
const UserModel = require('../models/users/index');
const user = new UserModel({
forename: 'Tom',
surname: 'Kiernan',
password: 'test',
email: 'test#example.com',
organisation: '5d9e1a87cb220e7c64e7f8fb',
});
user.save(err => {
if( err ) {
console.log( err );
}
console.log( user );
});
Not specifically sure why it is only autogenerating the id and a version number what is happening to the rest of the info?
Also as you may notice in the code above I am error logging the save function and it is not returning any errors.

So I found my mistake because of a comment by #CuongLeNgoc
In model file I was requiring the model it's own file and trying to use it as the Schema.
Below is the updated file with notes
const mongoose = require('../../db/index');
// const UserSchema = require('../../models/users/index'); //Wrongly requiring the model again.
const UserSchema = require('../../schema/users/index'); // correctly requiring the schema
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;

Related

How can I see the products per each category with mongoose

this is my schema for storing products using mongoose as below.
const mongoose = require("mongoose");
const mongoosePaginate = require("mongoose-paginate-v2");
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: {
type: String,
required: true,
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category",
},
productImage: {
type: String,
required: true,
},
description: {
type: String,
},
createdAt: {
type: Date,
default: new Date(),
},
deletedAt: {
type: Date,
},
});
productSchema.plugin(mongoosePaginate);
const productModel = mongoose.model("Product", productSchema, "Product");
module.exports = productModel;
and this how I have the schema for storing categories that products are related to
const mongoose = require("mongoose");
const categorySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
product: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
});
const categoryModel = mongoose.model("Category", categorySchema, "Category");
module.exports = categoryModel;
What I don´t know is how to populate my controller.
getAll: async (req, res) => {
const limitPage = parseInt(req.query.limit, 10) || 10;
const pageChange = parseInt(req.query.page, 10) || 1;
Product.paginate({}, { limit: limitPage, page: pageChange })
.then((result) => {
return res.status(200).json({
message: "GET request to all getAllProducts",
dataCount: result.length,
result: result,
});
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
},
Please help, I don´t understand why it not being populated and how to see the categories displayed with the categorie they belong to.
You should probably include populate in your query like so:
...
Product.paginate({}, { limit: limitPage, page: pageChange }).populate('category')
...
Note: Are you sure you want to have a 1-1 relation between products and categories. Because this is what you achieve if you set the relation like you did on both schemas. If yes, you should find a way to ensure that this 1-1 relation is enforced each time you save or update objects.

How can I integrate MongoDB $addFields aggregation in the backend and frontend?

React Front-end
// ADD CUSTOM FILED FUNCTION
const handleCustomFiled = () => {
const FieldContainer = document.querySelector(".custom-filed-container");
const input = document.createElement("input");
const label = document.createElement("label");
label.id = "custom-label";
label.innerText = "Custom Filed";
label.setAttribute("contenteditable", "true");
FieldContainer.appendChild(label);
FieldContainer.appendChild(input);
};
Backend code
const mongoose = require("../connection");
const Schema = mongoose.Schema;
const personSchema = new Schema({
firstName: String,
lastName: String,
birthDay: String,
gender: String,
pronouns: String,
relationship: String,
user: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
username: String,
},
});
module.exports = mongoose.model("Person", personSchema);

Subdocument not being saved in its own collection - Mongoose

I found this on the documentation for mongoose:
Subdocuments have save and validate middleware just like top-level
documents. Calling save() on the parent document triggers the save()
middleware for all its subdocuments, and the same for validate()
middleware.
But that hasn't been working for me. when I call save on my parent, the subdocument doesn't get created in its own collection. Here's my code:
Cart Model
const mongoose = require("mongoose");
const cartSchema = new mongoose.Schema({
numOfSessions: {
type: Number,
required: true
},
status:{
type: String,
enum: ["completed", "active", "deleted"],
required: true
}
}, { timestamps: true, versionKey: false });
const Cart = mongoose.model('shoppingCart', cartSchema);
module.exports = Cart;
User Model
const mongoose = require("mongoose");
const Cart = require("./xxxx").schema
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true
},
shoppingCarts: [ Cart ]
}, { timestamps: true, versionKey: false });
const User = mongoose.model('user', userSchema);
module.exports = User;
Server Side
const new_user = new User({
firstName: req.body.firstname,
lastName: req.body.lastname,
username: req.body.username,
phoneNum: req.body.phone,
userType: req.body.userType,
email: req.body.email,
password: hashedPassword
});
new_user.shoppingCarts.push(new_cart);
console.log('pushed')
new_cart.save(); //If i take out this line, this subdocument doesn't get saved
new_user.save()
.then((result) => {
console.log(result);
});
To save the subdocument, I'm having to call save on it them well. Is this how it's supposed to be? Thx :D

Query wont return data from relationship

I'm following this video series.
Here i have problem with getting data about user who created the event in following script
here's my app.js
const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql')
const { buildSchema } = require('graphql');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Event = require('./models/event');
const User = require('./models/user');
const app = express();
const conString = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}#clusterpl-qiufl.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority`
app.use(bodyParser.json());
app.use(
'/graphql',
graphqlHttp({
schema: buildSchema(`
type Event {
_id: ID!
title: String!
description: String!
price: Float!
date: String!
creator: User!
}
type User {
_id: ID!
email: String!
password: String!
createdEvents: [Event!]
}
input UserInput {
email: String!
password: String!
}
input EventInput {
title: String!
description: String!
price: Float!
date: String!
}
type RootQuery {
events: [Event!]!
}
type RootMutation {
createEvent(eventInput: EventInput): Event
createUser(userInput: UserInput): User
}
schema {
query: RootQuery,
mutation: RootMutation
}
`) ,
rootValue: {
events: () => {
return Event.find().populate('creator')
.then(events => {
console.log(events)
return events.map(event => {
console.log(event)
return {
...event._doc,
_id: event.id
};
});
})
.catch(err => {
throw err;
})
},
..
},
graphiql: true
})
);
mongoose.connect(conString, {useNewUrlParser: true}).then(
() => {console.log('Success !')},
err => { console.log(err) }
)
app.listen(3000);
user.js and event.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
createdEvents: [
{
type: Schema.Types.ObjectId,
ref: 'Event'
}
]
});
module.exports = mongoose.model('User', userSchema)
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const eventSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
date: {
type: Date,
required: true
},
creator: [
{
type: Schema.Types.ObjectId,
ref: 'User'
}
]
});
module.exports = mongoose.model('Event', eventSchema);
once i submit this graphql query
query{
events {
creator {
email
}
}
}
returns "message": "Cannot return null for non-nullable field User.email.",
I'm completly new to graphql and any answer would be much appreciate.
maybe this might helps someone else, i don't know what happens there but i got expected results, by adding
const user = userId => {
return User.findById(userId).then(user => {
return { ...user._doc, _id: user.id };
})
.catch(err => {
throw err;
});
}
method and used it in event resolver function like this
events: () => {
return Event.find()
.populate('creator')
.then(events => {
return events.map(event => {
console.log('ev',event._doc)
return {
...event._doc,
_id: event.id,
// creator: {
// ...event._doc.creator._doc,
// _id: event._doc.creator.id
// }
creator: user.bind(this, event._doc.creator)
};
})
})
.catch(err => {
throw err;
})
},

Populate and only return that populated value

I am trying to just return the populated profile document from the User Document. But I can't seem to code in the logic correctly...What is the way to go about this? I only want to select the profile field to return from the user. I thought of maybe trying .select("profile).populate({ path: "profile"}), but that didn't work either.
User.findOne({ _id: req.user._id })
.populate({ path: "profile"}) <---
.then(user => {
res.json(user);
})
.catch(() => res.json({ Error: "User Account type is not valid" }));
User Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
profile: {
type: Schema.Types.ObjectId,
refPath: "profile_type"
},
profile_type: {
type: String,
enum: ["PartnerAdminProfile", "DistrictAdminProfile", "MentorProfile"]
},
});
module.exports = User = mongoose.model("User", UserSchema);
Profile Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const PartnerAdminProfileSchema = new Schema({ <----EDIT redefined schema name
user: {
type: Schema.Types.ObjectId,
ref: "User"
},
profile_picture: {
type: Schema.Types.ObjectId,
ref: "Image",
date: {
type: Date,
default: Date.now
}
}
});
module.exports = PartnerAdminProfile = mongoose.model("PartnerAdminProfile", PartnerAdminProfilechema);
expected output:
profile: {
user: "6546556654564",
profile_picture :{url:https://test.jpg}
}