How to save multilanguage data in moongoose? - node.js

i try to learn Mean.js and i need to use multilanguage support in my app.
I chose this schema to save data
"_id": {
"name": {
en: "English",
fr: "Français"
}
}
in my server model:
var KnowledgeSchema = new Schema({
name: {
en: {
type: String,
default: '',
required: 'Please fill Knowledge name',
trim: true
},
fr : {
type: String,
default: '',
required: 'Please fill Knowledge name',
trim: true
}
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Knowledge', KnowledgeSchema);
and controller
exports.create = function(req, res) {
var knowledge = new Knowledge(req.body);
knowledge.user = req.user;
knowledge.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(knowledge);
}
});
};
What i need for save "en" and "fr" into "name" ?

Related

Nodejs:Array data not added in mongodb

This is my model profile.js
var mongoose = require('mongoose');
const ProfileSchema = mongoose.Schema({
educationinfo: [{
universityname:
{
type: String,
required: true
},
degree:
{
type: String,
required: true
},
coursecompletionyear:
{
type: String,
required: true
},
collegename:
{
type: String,
required: true
},
specialization:
{
type: String,
required: true
},
marks:
{
type: String,
required: true
},
courselevel:
{
type: String,
required: true
}
}]
});
const Profile = module.exports = mongoose.model('Profile', ProfileSchema);
This is my route.js post function
router.post('/addprofiledetails', function(req, res, next) {
let newProfile = new Profile({
$educationinfo:[{
universityname:req.body.universityname,
degree:req.body.degree
}]
});
newProfile.save((err, profile) => {
if (err) {
res.json({ msg: 'Failded to add profiledetails' });
} else {
res.json({ msg: 'successfully add profile details' });
}
});
});
I got success msg in post function but the data not added in mongodb. i don't know where i did mistake .please help me.
In mongoDB I got data like,
{
"educationinfo": [],
"_id": "5bed14b93a107411a0334530",
"__v": 0
}
I want details inside educationinfo, please help.
You need to change schema definition and query.
1.remove required from schema Or apply required to those field that you must provide value.
educationinfo: [{
universityname:
{
type: String,
// required: true
},
degree:
{
type: String,
//required: true
},
coursecompletionyear:
{
type: String,
// required: true
},
collegename:
{
type: String,
// required: true
},
specialization:
{
type: String,
//required: true
},
marks:
{
type: String,
// required: true
},
courselevel:
{
type: String,
// required: true
}
}]
2.change $educationinfo with educationinfo
educationinfo:[{
universityname:req.body.universityname,
degree:req.body.degree
}]
Since you marked the properties of educationinfo as required, you need to provide them when you create an instance of Profile. If you don't want to do that you need to remove the required property from those properties that you won't be supplying on instance creation like below:
const mongoose = require('mongoose');
const ProfileSchema = mongoose.Schema({
educationinfo: [{
universityname:
{
type: String,
required: true
},
degree:
{
type: String,
required: true
},
coursecompletionyear:
{
type: String
},
collegename:
{
type: String
},
specialization:
{
type: String
},
marks:
{
type: String
},
courselevel:
{
type: String
}
}]
});
const Profile = module.exports = mongoose.model('Profile', ProfileSchema);
After making those changes, you need to make one more change in your POST route, change $educationinfo to educationinfo
router.post('/addprofiledetails', function(req, res, next) {
const newProfile = new Profile({
educationinfo:[{
universityname: req.body.universityname,
degree: req.body.degree
}]
});
newProfile.save((err, profile) => {
if (err) {
res.json({ msg: 'Failded to add profiledetails' });
} else {
res.json({ msg: 'successfully add profile details' });
}
});
});
The data you insert is incomplete.
The properties in your schema marked as required: true need to be inserted aswell. Because you do not meet the schema requirements, it is failing.

Mongoose doesn't save all the fields of my POST request

I have a very simple "social network" app: users can register, write posts, like/unlike them and comment a post.
I have a probleme with my Post Schema :
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
},
],
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
},
{
text: {
type: String,
required: true,
},
},
{
name: {
type: String,
},
},
{
avatar: {
type: String,
},
},
{
date: {
type: Date,
default: Date.now,
},
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model("post", PostSchema);
When I receive my POST request for comments...
// #route POST api/posts/comment/:id
// #desc Add comment to post
// #access Private
router.post(
"/comment/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
const { errors, isValid } = validatePostInput(req.body);
// Check Validation
if (!isValid) {
// If any errors, send 400 with errors object
return res.status(400).json(errors);
}
Post.findById(req.params.id)
.then(post => {
const newComment = {
text: req.body.text,
name: req.body.name,
avatar: req.body.avatar,
user: req.user.id,
};
console.log("newComment: ", newComment);
// Add to comments array
post.comments.unshift(newComment);
console.log("post: ", post.comments);
// Save
post.save().then(post => res.json(post));
})
.catch(err => res.status(404).json({ postnotfound: "No post found" }));
},
);
The only fields that are saved in the post.comments array is the User. Not the other fields (text, name, avatar, date).
My console.log("newComment: ", newComment); properly returns the complete object with all its properties but then, 2 lines below, console.log("post: ", post.comments); only returns the comment _id and the user and those are the only fields saved in the DB...
What did I miss here?
There is some Problem in the creation of the schema structure, this is the correct way:
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
}
]
the valid structure is nothing but like this(showing the changes made above):
comments: [{
user: {},
text: {},
// others...
}]

mongoose js populate embedded objects in array

I am trying to display a list of subject names associated with a training event, however the object id is the only property that is populated after the query has executed. I have tried the solution in this QUESTION which seems to be similar to what I am trying to achieve, but it is not working.
My load method is at the very bottom of this code snippet.
Any help is appreciated, thanks.
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
}
});
var SubjectSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill subject name',
trim: true
},
description: {
type: String,
default: '',
required: 'Please fill subject description',
trim: true
}
});
var TrainingSubjectSchema = new Schema({
subject: {
type: Schema.ObjectId,
ref: 'Subject'
},
attendanceRate:[{
type: Number
}]
});
var TrainingEventSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill training event name',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
attendees:[{
type: Schema.ObjectId,
ref: 'User'
}],
subjects:[TrainingSubjectSchema]
});
// retrieve method
Training.findById(id).populate('user', 'displayName').populate('subjects.subject','name').exec(function(err, trainingevent)
Not sure why it is not working in your side but I have tried
in my code and it is working as expected.
Here it is how I am creating the Schemas:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost:27017/mongoose_benn');
var UserSchema = new Schema({
firstName: {type: String, trim: true, default: ''},
lastName: {type: String, trim: true, default: ''},
displayName: {type: String, trim: true}
});
var SubjectSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill the subject name.',
trim: true
},
description: {
type: String,
default: '',
required: 'Please fill subject description',
trim: true
}
});
var TrainingSubjectSchema = new Schema({
subject: {type: Schema.ObjectId, ref: 'Subject'},
attendanceRate: [{type: Number}]
});
var TrainingEventSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill the training event name.',
trim: true
},
created: {type: Date, default: Date.now},
user: {type: Schema.ObjectId, ref: 'User'},
attendes: [{
type: Schema.ObjectId,
ref: 'User'
}],
subjects: [TrainingSubjectSchema]
});
module.exports = {
User: mongoose.model('User', UserSchema),
Subject: mongoose.model('Subject', SubjectSchema),
TrainingSubject: mongoose.model('TrainingSubject', TrainingSubjectSchema),
TrainingEvent: mongoose.model('TrainingEvent', TrainingEventSchema)
};
And here I am processing data with the models:
var async = require('async');
var models = require('./models.js');
var User = models.User;
var Subject = models.Subject;
var TrainingSubject = models.TrainingSubject;
var TrainingEvent = models.TrainingEvent;
async.waterfall(
[
clearDB.bind(null, {collections: [User, Subject, TrainingSubject, TrainingEvent], async: async}),
createUsers.bind(null, {User: User, async: async}),
createSubjects.bind(null, {async: async, Subject: Subject}),
createTrainingEvents.bind(null, {async: async, TrainingEvent: TrainingEvent}),
showTrainingEvents.bind(null, {TrainingEvent: TrainingEvent})
]
);
function createTrainingEvents(data, db, next) {
var firstSubject = db.subjects[0];
var secondSubject = db.subjects[1];
var trainingSubjects = [
{
subject: firstSubject._id,
attendanceRate: [5, 5]
},
{
subject: secondSubject._id,
attendanceRate: [4, 4, 5]
}
];
var trainingEvents = [
{
name: 'October Fest',
user: db.users[0]._id,
subjects: [trainingSubjects[0]],
attendes: [db.users[0]._id, db.users[1]._id]
},
{
name: 'August Fest',
user: db.users[1]._id,
subjects: [trainingSubjects[1]],
attendes: [db.users[0]._id, db.users[1]._id]
}
];
data.async.map(
trainingEvents,
function(trainingEvent, done) {
data.TrainingEvent.create(trainingEvent, done);
},
function(err, result) {
next(err);
}
);
}
function clearDB(data, next) {
async.map(
data.collections,
function(collection, done) {
collection.remove({}, done);
},
function(err) {
next(err);
}
);
}
function createUsers(data, next) {
var users = [
{firstName: 'Wilson', lastName: 'Balderrama', displayName: 'Wily'},
{firstName: 'Santiago', lastName: 'Balderrama', displayName: 'Santi'},
{firstName: 'Keila', lastName: 'Balderrama', displayName: 'Kei'}
];
data.async.map(
users,
function(user, done) {
data.User.create(user, done);
},
function(err, results) {
next(err, {users: results});
}
);
}
function showUsers(data, next) {
data.User.find({}, function(err, users) {
next();
});
}
function createSubjects(data, db, next) {
var subjects = [
{
name: 'JavaScript for Beginners',
description: 'JS fundamentals'
},
{
name: 'Node.JS for Beginners',
description: 'Node.JS streams'
}
];
data.async.map(
subjects,
function(subject, done) {
data.Subject.create(subject, done);
},
function(err, result) {
db.subjects = result;
next(err, db);
}
);
}
function createTrainingSubjects(data, db, next) {
var firstSubject = db.subjects[0];
var secondSubject = db.subjects[1];
var trainingSubjects = [
{
subject: firstSubject._id,
attendanceRate: [5, 5]
},
{
subject: secondSubject._id,
attendanceRate: [4, 4, 5]
}
];
data.async.map(
trainingSubjects,
function(trainingSubject, done) {
data.TrainingSubject.create(trainingSubject, done);
},
function(err, result) {
db.trainingSubjects = result;
next(err, db);
}
);
}
function showTrainingSubjects(data, next) {
data.TrainingSubject
.find({})
.populate('subject')
.exec(function(err, data) {
next();
});
}
function showSubjects(data, next) {
data.Subject.find({}, function(err, data) {
next();
});
}
function showTrainingEvents(data, next) {
data.TrainingEvent
.find({name: 'August Fest'})
.populate('user', 'displayName')
.populate('subjects.subject', 'name')
.exec(function(err, data) {
console.log(JSON.stringify(data));
next();
});
}
And the output is;
[
{
"_id":"55981d58cfd48c905c3a5fde",
"user":{
"_id":"55981d58cfd48c905c3a5fd8",
"displayName":"Santi"
},
"__v":0,
"subjects":[
{
"subject":{
"_id":"55981d58cfd48c905c3a5fdb",
"name":"Node.JS for Beginners"
},
"_id":"55981d58cfd48c905c3a5fdf",
"attendanceRate":[
4,
4,
5
]
}
],
"attendes":[
"55981d58cfd48c905c3a5fd7",
"55981d58cfd48c905c3a5fd8"
],
"created":"2015-0704T17:52:24.181Z",
"name":"August Fest"
}
]

Mongoosejs : Populate doesn't return any data

Hi I'm new in mongoose and I have a problem with populate collection it doesn't return any data, I don't know why here's my code:
Company Model
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Agent = mongoose.model('Agent'),
DBRef = mongoose.SchemaTypes.DBRef;
/**
* Company Schema
*/
var CompanySchema = new Schema({
name: {
type: String,
default: '',
//required: 'Please fill Company name',
trim: true
},
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
address: {
type: String,
default: '',
//required: 'Please fill Company address',
trim: true
},
locked: {
type: Boolean,
default: true,
},
deleted: {
type: Boolean,
default: false,
},
logo: {
type: String,
default: '',
},
email: {
type: String,
default: '',
index: { unique: true }
//required: 'Please fill Company email',
},
tel: {
type: String,
default: '',
//required: 'Please fill Company tel',
},
fax: {
type: String,
default: '',
//required: 'Please fill Company fax',
},
type: {
type: String,
//required: 'Please fill Company type',
trim: true
},
description: {
type: String,
default: '',
trim: true
},
validator: {
type: Schema.ObjectId,
ref: 'User'
},
admins: [Agent]
});
module.exports = mongoose.model('Company', CompanySchema);
Agent Model
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
//Company = mongoose.model('Company'),
DBRef = mongoose.SchemaTypes.DBRef;
/**
* Agent Schema
*/
var AgentSchema = new Schema({
// Agent model fields
// ...
firstname: {
type: String,
default: ''
},
lastname: {
type: String,
default: ''
},
email: {
type: String,
default: '',
index: { unique: true }
},
password: {
type: String,
default: ''
},
roles: {
type: Array,
},
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
deleted: {
type: Boolean,
default: false
},
locked: {
type: Boolean,
default: false
},
workFor: {
type: Schema.ObjectId,
ref: 'Company'
}
});
module.exports = mongoose.model('Agent', AgentSchema);
Populate Code
Company.findById(id).populate('admins').exec(function(err, company) {
if (err) return next(err);
if (!company) return next(new Error('Failed to load Company ' + id));
console.log(company.admins);
req.company = company ;
next();
});
thanks :) .
your schema definition of company actually defines that the agents are embedded into the company document, not referenced. If you want references that you then could populate you should use something like this:
var CompanySchema = new Schema({
....
admins: [{type: Schema.Types.ObjectId, ref: 'Agent'}],
....
thnks reto, here is the saving code of company :
/**
* Create a Company
*/
exports.create = function(req, res) {
var company = new Company(req.body);
User.findById('54e22d19aae0cff01a47df96',function(err,user){
if (err) {
return res.status(400).send({
messages: errorHandler.getErrorMessage(err)
});
}
company.user = user;
req.checkBody('name', 'please fill the name').notEmpty();
req.checkBody('address', 'please fill the address').notEmpty();
req.checkBody('tel', 'please fill a correct phone').notEmpty().isNumeric();
req.checkBody('type', 'please fill the type').notEmpty();
req.checkBody('email', 'please fill a correct email').isEmail();
req.checkBody('admin.firstname', 'please fill the admin firstname').notEmpty();
req.checkBody('admin.lastname', 'please fill the admin lastname').notEmpty();
req.checkBody('admin.email', 'please fill a correct admin email').isEmail();
req.checkBody('admin.password', 'please fill the admin password').notEmpty();
var errors = req.validationErrors();
if (errors) {
return res.status(400).send({
messages: errors
});
}else{
company.save(function(err) {
if (err) {
return res.status(400).send({
messages: errorHandler.getErrorMessage(err)
});
} else {
var agents = preapareAgents(req,company);
Agent.create(agents,function(err){
if(err){
return res.status(400).send({
messages: errorHandler.getErrorMessage(err)
});
}else{
res.jsonp({company: company, agents: agents});
}
});
}
});
}
});
};

mongoose save embedded document

I have the following schema:
var StorySchema = new Schema({
title: { type: String, required: true },
users: {
id: { type: Schema.ObjectId, ref: 'Users' },
creator: { type: Boolean }
},
maxlines: { type: Number, default: '10'},
lines: {
text: { type: String },
entered_at: { type: Date },
user: {
id: { type: Schema.ObjectId, ref: 'Users' }
}
},
created_date: { type: Date, default: Date.now },
updated_date: { type: Date, default: Date.now },
})
I want to push data into lines and am trying to do so with the below update:
exports.update = function (req, res) {
Stories
.findOne({ _id: req.params.id }, function (err, story) {
if (err) {
res.json(200, {
success: "false",
message: err.message
})
} else {
story.maxlines = story.maxlines - 1
story.lines.push ({
text : req.body.text,
'user.id' : req.headers.id,
entered_at : new Date().toISOString()
})
story.save(function(err, story) {
if (err) {
res.json(200, {
success: "false",
message: err.message
})
} else if (story) {
res.json({
sucess: "true",
message: story
})
}
})
}
})
}
I get an error of TypeError: Object { user: {} } has no method 'push', not entirely sure how to update the lines and the user associated with the line
Because story.lines is not an Array. You probably need to update the Schema to convert the lines to type Array in this way:
var LineSchema = new Schema({
text: {
type: String
},
entered_at: {
type: Date
},
user: {
id: {
type: Schema.ObjectId,
ref: 'Users'
}
}
});
var StorySchema = new Schema({
title: {
type: String,
required: true
},
users: {
id: {
type: Schema.ObjectId,
ref: 'Users'
},
creator: {
type: Boolean
}
},
maxlines: {
type: Number,
default: '10'
},
lines: [LineSchema],
created_date: {
type: Date,
default: Date.now
},
updated_date: {
type: Date,
default: Date.now
},
})

Resources