I'm using Feathers.js with Mongoose and I want to create a field that cannot be changed by the services.
// account-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
require('mongoose-type-email');
module.exports = function(app) {
const mongooseClient = app.get('mongooseClient');
const recovery = new mongooseClient.Schema({
token: { type: String, required: true }
}, {
timestamps: true
});
const account = new mongooseClient.Schema({
firstName: { type: String, required: true },
surname: { type: String, require: true },
phone: { type: String, require: true },
email: { type: mongoose.SchemaTypes.Email, required: true, unique: true },
birth: { type: Date, required: true },
gender: { type: String, required: true },
country: { type: String, required: true },
address: { type: String, required: true },
address2: { type: String, required: false },
city: { type: String, required: true },
postcode: { type: String, required: true },
password: { type: String, required: true },
status: { type: String, required true }
}, {
timestamps: true
});
return mongooseClient.model('account', account);
};
No one can make a post at /account/<id> and change the field status.
This field should only be changed when internally. When some approval service request.
How can I implement this behavior?
This is a perfect use case for Feathers hooks. When accessed externally, in a service method call params.provider will be set so you can check for it and remove the field from data if it is:
module.exports = function() {
return async context => {
if(context.params.provider) {
delete context.data.status;
}
}
}
This hook will be a before hook for the create, update and patch method.
Related
I want to enter data via Postman into an array form using id Collection in the database also how can I write a valid JSON script for the modal for the modal
Add data using id Collection
controller
const addAcademicExperience = async (req, res, next) => {
//const id = req.params.id;
const {AcademicExperience} = req.body;
let academicexperience;
try {
academicexperience = await AcademicExperience.findByIdAndadd(id, {
AcademicExperience
});
await academicexperience.save();
} catch (err) {
console.log(err);
}
if (!academicexperience) {
return res.status(404).json({ message: 'Unable to Add' })
}
return res.status(200).json({academicexperience});
model Schema
Some data is required in an array and some are not
per user per user
To clarify, the site is similar to LinkedIn
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const FacultySchema = new Schema({
Faculty_ID: {
type: Number,
required: true,
unique: true,
},
Name: {
type: String,
required: true,
},
Phone_Number: {
type: String,
required: true,
},
Email: {
type: String,
required: true,
},
AcademicExperience: [{
institution: { type: String, required: true },
rank: { type: String, required: true },
title: { type: String, required: true },
working: { type: Boolean, required: true },
}
],
Certifications:
{
type: String,
require: true,
},
Currentm_embership:
{
type: String,
require: true,
},
Servicea_ctivites:
{
type: String,
require: true,
},
Professional:
{
type: String,
require: true,
},
Education:[ {
degree: { type: String, required: true },
discpilne: { type: String, required: true },
institution: { type: String, required: true },
year: { type: Date, required: true },
}
],
Non_academic_experines:[
{
Company: { type: String, required: true },
title: { type: String, required: true },
working: { type: Boolean, required: true },
Description_of_position: { type: String, required: true },
}
],
Honoers_and_awards:
{
type: String,
require: true,
},
Puplications_and_presentation:
{
type: String,
require: true,
},
});
module.exports = mongoose.model("Faculty", FacultySchema);
I am currently working on a user registration setup. In the user model, I have defined apiKey as a property of the user and I want to set it equal to the user object Id. How can I do this ? Here is my code for the model :
const userScheama = new mongoose.Schema(
{
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
name: {
type: String,
trim: true,
required: true
},
hashed_password: {
type: String,
required: true
},
apiKey:{
type: String,
required: false,
},
plan:{
type: String,
required: false
},
salt: String,
role: {
type: String,
default: 'subscriber'
},
resetPasswordLink: {
data: String,
default: ''
}
},
{
timestamps: true
}
);
You can use mongoose hooks here. First you need to update your apiKey to apiKey: {type:Schema.Types.ObjectId required: false }, and then add the below code to your model file
userScheama.pre('save', async function (next) {
this.apiKey = this._id;
next();
});
I am using nodejs,mongodb and mongoose. This query is not fetching match data from user and order table. I have read mongoose docs and alot of other articeles. It's according to it but doesn't fetch match data from tables.
Query code:
const data = await order
.find({ admin_id: req.params.id })
.populate("orderRelate");
console.log(data);
My user and order schema code is:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
mobile_no: { type: Number, required: true },
profilePic: { type: String, defaut: "" },
owner: { type: Boolean, defaut: false },
},
{ timestamps: true }
);
const orderSchema = new mongoose.Schema(
{
customer_id: { type: String, required: true },
admin_id: { type: String, required: true },
order_type: { type: String, defaut: "normal" },
order_status: { type: String, required: true },
order_price: { type: Number, required: true },
order_address: { type: String, required: true },
order_pickDate: { type: String, required: true },
order_pickTime: { type: String, required: true },
orderRelate: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
module.exports = mongoose.model("Order", orderSchema);
Please let me know if anyone know why I am facing this issue.
Thanks
Please try with findById maybe it's work
i don't know how you wrote your middleware function but..
await Order.find({orderRelate: req.user.id})
In my NodeJS API and MongoDB, I'm trying to delete a record which is a reference to another collection.
What I would like to do is to delete the referred objectId and the records related to the other collection which is referred.
I have 2 models Profiles and Posts and I want to delete the same one post from Profile and Post collection.
I was able to delete the reference id in Profile but I don't know how to delete also the record from Posts collection.
I tried this:
async delete(req, res) {
try {
// Match with username and pull to remove
await Profile.findOneAndUpdate(
{ _id: res.id._id },
{ $pull: { posts: req.params.postId } },
err => {
if (err) {
throw new ErrorHandlers.ErrorHandler(500, err);
}
res.json({ Message: "Deleted" });
}
);
} catch (error) {
res.status(500).send(error);
}
}
And my 2 models:
// Here defining profile model
// Embedded we have the Experience as []
const { Connect } = require("../db");
const { isEmail } = require("validator");
const postSchema = {
type: Connect.Schema.Types.ObjectId,
ref: "Post"
};
const experienceSchema = {
role: {
type: String,
required: true
},
company: {
type: String,
required: true
},
startDate: {
type: Date,
required: true
},
endDate: {
type: Date,
required: false
},
description: {
type: String,
required: false
},
area: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now,
required: false
},
updatedAt: {
type: Date,
default: Date.now,
required: false
},
username: {
type: String,
required: false
},
image: {
type: String,
required: false,
default: "https://via.placeholder.com/150"
}
};
const profileSchema = {
firstname: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
email: {
type: String,
trim: true,
lowercase: true,
unique: true,
required: [true, "Email is required"],
validate: {
validator: string => isEmail(string),
message: "Provided email is invalid"
}
},
bio: {
type: String,
required: true
},
title: {
type: String,
required: true
},
area: {
type: String,
required: true
},
imageUrl: {
type: String,
required: false,
default: "https://via.placeholder.com/150"
},
username: {
type: String,
required: true,
unique: true
},
experience: [experienceSchema],
posts: [postSchema],
createdAt: {
type: Date,
default: Date.now,
required: false
},
updatedAt: {
type: Date,
default: Date.now,
required: false
}
};
const collectionName = "profile";
const profileSchemaModel = Connect.Schema(profileSchema);
const Profile = Connect.model(collectionName, profileSchemaModel);
module.exports = Profile;
const { Connect } = require("../db");
const reactionSchema = {
likedBy: {
type: String,
unique: true,
sparse: true
}
};
const postSchema = {
text: {
type: String,
required: true,
unique: true,
sparse: false
},
profile: {
type: Connect.Schema.Types.ObjectId,
ref: "Profile",
},
image: {
type: String,
default: "https://via.placeholder.com/150",
required: false
},
createdAt: {
type: Date,
default: Date.now,
required: false
},
updatedAt: {
type: Date,
default: Date.now,
required: false
},
reactions: [reactionSchema],
comments: {
type: Connect.Schema.Types.ObjectId,
ref: "Comment",
required: false
}
};
const collectionName = "post";
const postSchemaModel = Connect.Schema(postSchema);
const Post = Connect.model(collectionName, postSchemaModel);
module.exports = Post;
Just add a query to remove the post after pulling it's ID from the profile collection:
async delete(req, res) {
try {
// Match with username and pull to remove
await Profile.findOneAndUpdate(
{ _id: res.id._id },
{ $pull: { posts: req.params.postId } },
// You don't need an error callback here since you are
// using async/await. Handle the error in the catch block.
);
await Posts.remove({ _id: req.params.postId });
} catch (error) {
// This is where you handle the error
res.status(500).send(error);
}
}
I need to get all docs from service collection and it's showing all records when i console content. In content collection there is field mids which is media id and all images are going to media collection. I need to get media url for specific service. But when i console content.mids it returns undefined .Do i need to change in query?
Code is attached for your reference.
// Controller
services: (req, res) => {
Posts.find({content_type:'service'}).then(function(content) {
console.log(content); //right
console.log(content.m_ids); //showing undefined
Media.findById(content.m_ids).then(media => {
res.render('default/services', {content: content, reqUrl: req.url});
});
})
}
Services Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Schema = new Schema({
content_type: {
type: String,
required: true,
maxlength:20
},
content_title: {
type: String,
required: true,
max:100
},
content_url: {
type: String,
required: true,
maxlength:200
},
content_description: {
type: String,
required: true,
},
content_full_description: {
type: String,
required: false,
},
pt_ids: {
type: String,
required: false,
},
pc_ids: {
type: String,
required: false,
},
m_ids: {
type: String,
required: false,
},
created_by_user_id: {
type: String,
default: 1,
},
created_on: {
type: Date,
default: Date.now
},
updated_on: {
type: Date,
default: Date.now
},
post_icon_svg: {
type: String,
required: false,
}
});
module.exports = {Posts: mongoose.model('content_data', PostsSchema )};
// Media Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MediaSchema = new Schema({
media_name: {
type: String,
required: true
},
media_title: {
type: String,
required: true
},
media_alt: {
type: String,
required: true
},
media_description: {
type: String,
required: false
},
media_url: {
type: String,
required: true,
unique: true
},
created_by_user_id: {
type: String,
default: 1,
},
created_on: {
type: Date,
default: Date.now
},
updated_on: {
type: Date,
default: Date.now
}
});
module.exports = {Media: mongoose.model('media', MediaSchema )};