Meteor: Add subdocument to existing record - javascript

I have the following Scheme:
dGroup = new SimpleSchema({
title: { type: String, optional: true },
element: { type: String, optional: true }
});
MongoDB.attachSchema(new SimpleSchema({
title: { type: String },
slug: { type: String, unique: true },
language: { type: String, defaultValue: "en" },
group: { type: [dGroup], optional: true },
}));
... and in the DB I got this:
{ "_id" : "ag9qXWpCYm87kZbEk", "title" : "Test", "slug" : "test", "language" : "en" }
Now I want to add a dGroup -> title:
updates['group.title'] = 'insert this as a new group title with no element';
MongoDB.update({ _id: Id }, { $push: updates }, function(error) { if(error) console.warn(error); });
But this doesn't work. So I need some help to add subdocuments in meteor in case they do not exist.

Try declaring your object first and push it properly, like this:
var newGroup = {
title: 'insert this as a new group title with no element'
};
MongoDB.update({ _id: Id }, { $push: {group: newGroup }}, function(error) { if(error) console.warn(error); });

Related

MongoDB query by document reference

I am building a search functionality based on an invoice Model. My search look like:
const { organization_id, start_date, end_date, search } = req;
const params = { organization_id };
params['$or'] = [
{ invoice_nr: { $regex: '^' + search, $options: 'i' } },
{ reference: { $regex: '^' + search, $options: 'i' } } ];
}
return this.model('Invoice').find({
...params,
created_at: {
$gte: start_date,
$lte: end_date
}
}).populate('patient_id', 'name last_name');
This works great and I can correctly query the document and find search by property invoice_nr or reference.
However I also want to query on the patient_id property by name or last_name. My problem is that patient_id is just a reference to another document.
Invoice Model:
organization_id: { type: mongoose.Types.ObjectId, required: true, ref: 'Organization' },
invoice_nr: { type: String, required: true },
reference: { type: String, required: true },
patient_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Patient',
required: true,
},

How to save data in mongoDB and Schema is like bellow

Here is my schema by using mongoose npm package.
var StatusSchema = new mongoose.Schema({
empName: {
projectName: { type: String },
clientName: { type: String },
statusLastWeek: { type: String },
statusThisweek: { type: String },
planNextWeek: { type: String }
}
});
Here is my nodejs code to update the data
var Status = mongoose.model('Status', StatusSchema);
module.exports = Status;
Description: Want save data in MongoDB, data schema is like above mentioned,
save saving data is sored loke as bellow.
Inside Mongo DB :
{ "_id" : ObjectId("5d92f4aba4695e2dd90ab438"), "__v" : 0 }
{ "_id" : ObjectId("5d92f4b4a4695e2dd90ab439"), "__v" : 0 }
Expected collection in MongoDB :
Dave Smith {
projectName: BLE Mesh,
clientName: Tera,
statusLastWeek: BLE Scan,
statusThisweek: BLE List View,
planNextWeek: Mqtt config
}
Here you can see my NodeJS code :
router.post ('/update', (req,res,next)=>{
userStatus = new wkStatus(req.body)
userStatus.save()
.then(status => {
res.redirect('/success');
console.log ("Status saved in DB")
})
.catch(err => console.log(err))
// return next;
});
//You can use ODM like mongoose and define a schema with mongoose.Schema. You can just
// see mongoose module document from npm. Use .save() for save an object in DB.
// Example :
// schema as admin
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const sha256 = require('sha256')
const adminSchema = new Schema({
fullName: { type: String, required: true },
userName: { type: String },
noc: { type: String, required: true },
mobileNumber: { type: String, required: true },
email: { type: String },
chacommAddress: {
contactPerson: { type: String },
country: { type: String },
address: { type: String },
city: { type: String },
pinCode: { type: String },
state: { type: String },
stateCode: { type: String },
},
address: {
country: { type: String },
city: { type: String },
pinCode: { type: String },
state: { type: String },
stateCode: { type: String },
address: { type: String },
CIN: { type: String },
GSTIN: { type: String }
},
password: { type: String, required: true },
userType: { type: Number, required: true },
createdAt: { type: Date, required: true },
uploadFile: { type: String, required: true },
bankdetails: {
bankName: { type: String },
accountNo: { type: String },
ifscCode: { type: String },
accountType: { type: String },
accountName: { type: String },
cancelledChequeCopy: { type: String }
},
isActive: { type: Boolean },
invoiceString:{type:String},
invoiceValue:{type:Number},
accountantName :{type:String} ,
accountantDesignation : {type:String},
referredBy:{type:String}
});
adminSchema.methods.comparePassword = function (password) {
let password_hash = sha256(password);
return bcrypt.compareSync(password_hash, this.password);
}
adminSchema.pre('save', function (next) {
if (!this.isModified('password'))
return next();
let password_hash = sha256(this.password);
bcrypt.hash(password_hash, null, null, (err, hash) => {
if (err)
return next(err);
this.password = hash;
next();
});
});
//export schema
// module.exports = mongoose.model('Admin', adminSchema)
// for save:
const admin = require('admin')
var obj= new admin({
// values as per model defined
})
obj.save()
const wkStatus = new wkStatus({
_id: new mongoose.Types.ObjectId(),
projectName: req.body.projectName,
clientName: req.body.clientName,
statusThisweek: req.statusThisweek,
statusLastWeek: req.statusLastWeek,
planNextWeek: req.planNextWeek
})
Status
.save()
.then(result => {
res.status(201).json({
message: "Data Created Successfully",
})
console.log(result) // show the response
})
.catch(err => {
res.status(500).json({error:err})
})
Try this way hope it will work. If need more you can message me
The schema what you are trying to create itself is wrong.
empName: {
projectName: { type: String },
clientName: { type: String },
statusLastWeek: { type: String },
statusThisweek: { type: String },
planNextWeek: { type: String }
}
The above schema can create objects like below: "empName" cannot be dynamic.
empName: {
projectName: BLE Mesh,
clientName: Tera,
statusLastWeek: BLE Scan,
statusThisweek: BLE List View,
planNextWeek: Mqtt config
}
If you want to store like what you have shown, where empName dynamically then you should make empName as Map
See https://mongoosejs.com/docs/schematypes.html#maps

meteor: add some value to nested documents

I'm trying to add a value to a nested schema:
groups = new SimpleSchema({
title: { type: String, optional: true },
element: { type: [elements], optional: true }
});
elements = new SimpleSchema({
description:{ type: String, optional: true },
anything: { type: String, optional: true }
});
MongoDB.attachSchema(new SimpleSchema({
title: { type: String },
slug: { type: String, unique: true },
language: { type: String, defaultValue: "en" },
group: { type: [groups], optional: true },
}));
Now I want to add just a new element-description to an existing entry in the DB. I tried this, but it doesn't work.
Uncaught Error: When the modifier option is true, validation object must have at least one operator
var newElement = {
description: 'insert this as a new element description'
};
MongoDB.update({ _id: Id }, { $push: { 'group.element': newElement }}, function(error) { if(error) console.warn(error); });
Is it correct to use 'group.element' as a $push-parameter?
Update
I forgot the index of group: $push: { 'group.0.element': newElement }
Also I have to define elements before groups in the schema.

Mongoose - when use populate no records otherwise array of records

I'm learning MeanJS and I have problem with Mongoose. I have two models:
var CategorySchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Category name',
trim: true
},
slug: {
type: String,
default: '',
trim: true,
unique: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
articles: [{
type: Schema.ObjectId,
ref: 'Article'
}]
});
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
category: {
type: Schema.ObjectId,
ref: 'Category'
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
slug: {
type: String,
default: '',
trim: true,
unique: true
},
content: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
I'm saving articles like this:
exports.create = function(req, res) {
var article = new Article(req.body);
article.user = req.user;
article.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
Category.findById(article.category).exec(function(err, category) {
category.articles.push(article.category);
category.save(function(err, category) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(article);
}
});
});
}
});
};
and it's saving properly. The object looks like this:
{
"_id" : ObjectId("55b73bf97aa70c2c083655b0"),
"user" : ObjectId("55b115f35c7a03cc0e59d821"),
"articles" : [
ObjectId("55b73c017aa70c2c083655b2"),
ObjectId("55b73ee20bab5e8c0c7eadca")
],
"created" : ISODate("2015-07-28T08:23:21.562Z"),
"slug" : "motocycles",
"name" : "Motocycles",
"__v" : 2
}
and even when I'm counting records like {{ category.articles.length }} it's proper amount of articles in category and I can even print ObjectIds in the view. But when I add .populate('articles') like this:
exports.list = function(req, res) {
Category.find().sort('-created').populate('user', 'displayName').populate('articles').exec(function(err, categories) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(categories);
}
});
};
the length returns 0, ObjectIds disapears and I have no access to article properties just like there was no articles in category. Any ideas why is that happening?
Additional edit:
mongoose.model('Article', ArticleSchema);
mongoose.model('Category', CategorySchema);
It seems that the problem was with create function. I've changed few things and it started working:
exports.create = function(req, res) {
var article = new Article(req.body);
article.user = req.user;
article.save(function(err, savedArticle) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
Category.findById(article.category).exec(function (err, category) {
category.articles.push(savedArticle);
category.markModified('articles');
category.save(function (err, category) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(savedArticle);
}
});
});
}
});
};
I'm curious why it wasn't working even though Category object had proper Article ObjectId's.
First, some changes with regard to variables,schema instances and using ObjectId(The mongoose documentation isn't the best).
var categorySchema = new mongoose.Schema({
name: {
type: String,
required: 'Please fill Category name',
trim: true
},
slug: {
type: String,
trim: true,
unique: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: mongoose.Types.Schema.ObjectId,
ref: 'User'
},
articles: [{
type: mongoose.Types.Schema.ObjectId,
ref: 'Article'
}]
});
var articleSchema = new mongoose.Schema({
created: {
type: Date,
default: Date.now
},
category: {
type: mongoose.Types.Schema.ObjectId,
ref: 'Category'
},
title: {
type: String,
trim: true,
required: 'Title cannot be blank'
},
slug: {
type: String,
trim: true,
unique: true
},
content: {
type: String,
trim: true
},
user: {
type: mongoose.Types.Schema.ObjectId,
ref: 'User'
}
});
You need to export your models if you are using an MV* pattern with separate files for separate concerns. So...
exports.method = mongoose.model('Category',categorySchema);
exports.otherMethod = mongoose.model('Article',articleSchema);
. method and .otherMethod are from nodejs. Not sure about express equivalent or what express itself uses.
Then just name this file and require it using its path.

JavaScript object element is missing during Mongoose update query

I'm trying to update a new field of data into an existed document, but some of the data is not updating.
In my AngularJS controller:
$scope.tellUsMore = function(){
var data = {
businessPhone:$scope.usersData.phone,
businessEmail:$scope.usersData.email,
businessFb:$scope.usersData.fb,
businessTwitter:$scope.usersData.twitter,
businessInstagram:$scope.usersData.instagram,
businessAboutUs:$scope.usersData.aboutUs,
businessTags:$scope.tags,
businessFeatures:$scope.features,
businessLocation:$scope.usersData.location,
businessPriceRange:$scope.usersData.priceRange,
businessPreparationTimeRange:$scope.usersData.preparationTimeRange
}
console.log(data); //result below
Account.updateProfile(data)
.success(function() {
alert("DONE")
})
.error(function(error) {
console.log(error)
});
}
the console.log(data) result on chrome console tab
Object
businessAboutUs: "LOL"
businessEmail: "example#gmail.com"
businessFb: undefined
businessFeatures: Array[5]
businessInstagram: undefined
businessLocation: Object
businessPhone: "0123456789"
businessPreparationTimeRange: 2
businessPriceRange: 2
businessTags: Array[2]
businessTwitter: undefined
__proto__: Object
In my Node.js server
this.updateProfile = function(req, res, next){
var data = req.body;
console.log(data)//result below
User.update(req.user, {$set: { businessDetails:data }}, {upsert: true}, function(err,user){
res.status(200);
});
}
the console.log(data) result in my terminal
{ businessPhone: '0123456789',
businessEmail: 'example#gmail.com',
businessAboutUs: 'LOL',
businessTags:
[ { name: 'Marina Augustine',
email: 'm.augustine#exampleas.com',
image: 'http://lorempixel.com/50/50/people?0',
_lowername: 'marina augustine' },
{ name: 'Oddr Sarno',
email: 'o.sarno#exampleas.com',
image: 'http://lorempixel.com/50/50/people?1',
_lowername: 'oddr sarno' } ],
businessFeatures:
[ { id: 1, title: 'Do you accept credit card ?', selected: true },
{ id: 2,
title: 'Do you accept table reservation ?',
selected: false },
{ id: 3,
title: 'Do you provide Wi-Fi for your customer ?',
selected: false },
{ id: 4, title: 'Is your product Halal ?', selected: true },
{ id: 5,
title: 'Do you provide parking for your customer ?',
selected: true } ],
businessLocation: { latitude: 3.1168450143582223, longitude: 101.60914228515628 },
businessPriceRange: 2,
businessPreparationTimeRange: 2 }
However, this is what I got – only businessLocation updated to businessDetails, and the businessLocation is not even complete.
> db.users.find().pretty()
{
"_id" : ObjectId("554eb9a8bfa096290c9efa46"),
"companyName" : "t and co",
"email" : "example#gmail.com",
"password" : "$2a$10$79b.XztwEXgdCPDxTkg4ieICSkYyKw4uXG/2E0WShSZxXVdGdwObm",
"dateJoined" : ISODate("2015-05-10T01:51:36.120Z"),
"accountVerified" : false,
"locationVerified" : false,
"__v" : 0,
"businessDetails" : {
"businessLocation" : {
}
}
}
>
schema for user
var userSchema = new db.Schema({
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
companyName: String,
locationVerified: { type:Boolean, default:false},
accountVerified: { type:Boolean, default:false},
dateJoined: {type:Date, default:Date.now}
})
value of req.user
554eb9a8bfa096290c9efa46 this is an objectID in mongodb
You need to define the businessDetails subdoc in userSchema if you want to be able to update it:
var userSchema = new db.Schema({
email: { type: String, unique: true, lowercase: true },
password: { type: String, select: false },
companyName: String,
locationVerified: { type:Boolean, default:false},
accountVerified: { type:Boolean, default:false},
dateJoined: {type:Date, default:Date.now},
businessDetails: {
businessPhone: String,
businessEmail: String,
businessAboutUs: String,
businessTags: [],
businessFeatures: [],
businessLocation: {
latitude: Number,
longitude: Number
},
businessPriceRange: Number,
businessPreparationTimeRange: Number
}
})

Categories