Mongoose query in MEAN stack - angularjs

I've installed the MEAN stack using the yeoman generator and I would like to implement a query that returns true if a document with a given value for a specific property exists.
It this is the model:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var FirstSchema = new Schema({
field1: {
type: Number,
trim: true,
default: ''
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
});
var SecondSchema = new Schema({
field1: {
type: Number,
trim: true,
default: ''
},
field2: {
type: String,
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
});
mongoose.model('First', FirstSchema);
mongoose.model('Second', SecondSchema);
During the creation of Second objects, I assign the $scope.field2 = $stateParams.firstId;
The given query generated by yeoman in the client side is:
$scope.find = function() {
$scope.firsts = Firsts.query();
};
How query if First._id == Second.field2?

Related

Mongose array inside of array

I want to achieve like this:
On every user there's subject, and on every subject there's students.
user: [{ subjects: {subjectCode, description},[{students: {name, year, phone}}]}]
I already got the users -> subject side.
my problem now is how can i achieve to create students inside of subjects?
This is for my authentication.
User.js
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('user', UserSchema);
Every user can create subjects.
Subject.js
const mongoose = require('mongoose');
const SubjectSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
student: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'student',
},
],
title: {
type: String,
required: true,
},
description: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('subject', SubjectSchema);
In every subjects, there's should array of students.
Student.js
const mongoose = require('mongoose');
const StudentSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
name: {
type: String,
required: true,
},
year: {
type: String,
},
phone: {
type: String,
},
email: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('student', StudentSchema);

How to save nested array of objects data using mongoose?

So, I'm sending data from angular reactive form like:
Angular reactive form UI image
and
Data being sent to backend in browser console image
I have made schema for task as:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let taskSchema = new Schema({
taskId:{
type:String,
unique:true
},
task:{
type:String,
default:''
},
subTask:[{
type: Schema.Types.ObjectId,
ref: 'SubTask'
}]
}
module.exports = mongoose.model('Task',taskSchema);
Schema for Sub-Task as:
let subTaskSchema = new Schema({
title:String,
subSubTask:[{
type: Schema.Types.ObjectId,
ref: 'SubSubTask'
}]
})
module.exports = mongoose.model('SubTask',subTaskSchema);
Schema for Sub-Sub-Task as:
let subSubTaskSchema = new Schema({
title:String
})
module.exports = mongoose.model('SubSubTask',subSubTaskSchema);
Now,I'm confused about how to save nested array of objects data in mongodb using mongoose?
you can define your schema like this
const userSchema = new mongoose.Schema({
likedBooks: [{
type: mongoose.Types.ObjectId,
ref: 'books'
}],
email: {
type: String,
required: true
},
name: {
type: String,
required: true
}
});
exports.User = mongoose.model('users', userSchema);
then you can populate data by doing
user = User.find({ email: req.body.email }).populate('likedBooks');
here likedBooks contains _id of each book
const bookSchema = new mongoose.Schema({
isbn: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
author: {
type: String,
required: true
},
publisher: {
type: String,
default: ""
},
imageUrl: {
type: String,
required: true
},
description: {
type: String,
default: ""
}
});
exports.Book = mongoose.model('books', bookSchema);
for both schema i have not put _id as it is auto generated by mongodb and it is used as reference
The Object Model should look like this before saving.
{
taskId: 1,
task: 'Do something',
subTask: [{
title: 'Write a essay',
subSubTask: [{
title: 'Collect details to write an essay'
}]
}]
}
Hope it helps...

Insert new values in array in mongoose

Below code contains two schema now Grocery Schema contains array of users in which i want to store all users id which are related to itemName
I have no clue how to insert new values in mongodb
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var GrocerySchema= new Schema({
itemName: {
type: String,
required: true,
unique: true
},
completed: Boolean,
date: String,
users:[{user_id:{type:Schema.Types.ObjectId,ref:user}}]
});
grocerydata=mongoose.model('grocery',GrocerySchema);
var UserSchema = new Schema({
fname: {
type:String,
required:true
},
lname:{type:String},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', UserSchema);
I have used below code for saving the multiple values and set the value of array
var docs= {
itemName : req.body.item,
completed: true,
date: new Date(),
$push: {"users": {user_id: req.body._id}}
}
}
grocerydata.create(docs, function(err, results) {
if (err)
res.send(err);
console.log(results);
});
but I am not able to push the user_id in Grocery Please help me
Thanks in Advance!!
You have an error in your last snippet of code. var docs should be the following:
var docs={
itemName : req.body.item,
completed: true,
date: new Date(),
//you forgot to wrap $push in {}
{$push: {"users": {user_id: req.body._id}}}
}
Source

Mongo Giving 'duplicate key error' on non-unique fields

I am getting a MongoDB error when trying to insert a subdocument. The subdocs already have unique _ids, but an error is being thrown for a different, non-unique field that I don't want unique.
The error in Angular is: "Assets.serial already exist". How can I make this field contain duplicate values, and what is causing the model to assume it should be unique?
Here is my Mongoose model:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var AssetUrlSchema = new Schema({
name: {
type: String,
unique: false,
default: '',
trim: true
},
url: {
type: String,
unique: false,
default: 'http://placehold.it/75x75',
trim: true
},
}),
AssetSchema = new Schema({
serial: {
type: Number,
unique: false
},
urls: {
type: [AssetUrlSchema],
unique: false,
default: [
{ name: '', url: 'http://placehold.it/75x75' },
{ name: '', url: 'http://placehold.it/75x75' }
]
}
}),
/**
* Item Schema
*/
ItemSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please enter name',
trim: true
},
assets: {
type: [AssetSchema],
default: [],
unique: false
},
property: {
type: Schema.ObjectId,
zd: 'Please select a property',
ref: 'Property'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Item', ItemSchema);
And here is my 'save' method:
function(){
var i = 0, assets = [];
for (;i < 24;i++) {
assets.push({
serial: 1000+i,
urls: {
name: 'Asset Name ' + i,
url: 'http://placehold.it/75x75?'
}
});
}
item = new Items ({
name: 'FPO',
property: newPropId,
assets: assets
});
return item.$save(
function(response){ return response; },
function(errorResponse) {
$scope.error = errorResponse.data.message;
}
);
}
The first time I insert a document, it works fine. Any subsequent time, it fails with a 400 because the assets.serial field is not unique. However, I am specifically marking that field as unique:false.
The error in the mode console is:
{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: mean-dev.items.$assets.serial_1 dup key: { : 1000 }]
name: 'MongoError',
code: 11000,
err: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: mean-dev.items.$assets.serial_1 dup key: { : 1000 }' }
POST /api/items 400 14.347 ms - 41
Mongoose doesn't remove existing indexes so you'll need to explicitly drop the index to get rid of it. In the shell:
> db.items.dropIndex('assets.serial_1')
This will happen if you initially define that field unique: true but then later remove that from the schema definition or change it to unique: false.
If you're using MongoAtlas, you can go to the collection -> click 'indexes' -> on the index you want to delete, click 'drop index'
If you are in a dev/prototype mode, simply deleting the actual collection (after changing the unique:true to false for instance), will reset everything and mongoose will allow your duplicates.

Bad request in MEAN stack app trying to append to an array in a schema

I am trying to pass an array of interest rates to a mongoose schema consisting of accounts.
I want to store interest rates that change at certain dates.
However, when I trigger the create function my dev tools tell me I have done something bad:
**400 Bad Request**
I have been using this as a template.
The view: has been disconnected so that I only pass:
var interest = {
rate: 1,
date: Date.now()
};
The controller that does the updating:
// Create new Account
$scope.create = function() {
// Create new Account object
var account = new Accounts ({
name: this.name,
desc: this.desc,
interests: []
});
// PROBLEMATIC PART
// Store interest:
var interest = {
rate: 1,
date: Date.now()
};
account.interests.push(interest);
// PROBLEMATIC PART END
// Redirect after save
account.$save(function(response) {
$location.path('accounts/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
The mongoose schema:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
*
* Interest Rate Schema
*/
var InterestRate = new Schema({
rate:{
type: Number,
default: 0,
trim: true
},
date:{
type : Date,
default: '',
required: 'When is the interest to be updated',
trim: true
}
});
/**
* Account Schema
*/
var AccountSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Account name',
trim: true
},
desc:{
type: String,
default: '',
trim: true
},
interests:
[{ type : Schema.Types.ObjectId, ref: 'InterestRate' }],
amount:{
type: Number,
default:0,
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Account', AccountSchema);
you can try by leaving the interest rate as a frond end structure and not define it in the model, then in the account schema set interests as type of [] and just push the objects
var AccountSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Account name',
trim: true
},
desc:{
type: String,
default: '',
trim: true
},
interests:
type:[],
default:[]
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
just like this

Resources