Insert new values in array in mongoose - angularjs

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

Related

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...

Mongoose - Cannot Update update deeply nested Objects

var ItemSchema = new Schema({
item: {type: String, required: false},
ts: {type: String, required: true},
selldate: {type: Number, required: false},
replaced: [ReplaceSchema]
});
var ProductSchema = new Schema({
title: {type: String, required: true, trim: true}, //name of the products
artNo: {type: Number, required: true},
catId: {type: String, required: true},
productType: {type: String, required: true}, //physical, textbased or downloadable product | can be 'dl', 'txt', 'phy'
tid: {type: String, required: false}, //only needed for physical products for providing a tid
minItems: {type: Number, required: true},
ts: {type: Number, required: true}, // when was the product online
buyCount: {type: Number, required: true}, // baught how many times
description: {type: String}, //more about the product
price: {type: Number, required: true}, // how much?
discounts: [DiscountSchema], // discount objects
items: [ItemSchema],
images: [], // fullsize images of the product
thumbnails: [], // small preview images of the product
// isPublic: {type: Boolean, required: true}, // if product should be published or not
itemCount: {type: Number, required: false} // how many items exists on the product
});
var CategorySchema = new Schema({
name: {type: String, required: true},
ts: {type: Number, required: true},
products: [ProductSchema]
});
So you see its: Category -> products[] -> items[]
I want to update the Objects in items array in the database and set (at this time undefined field "selldate".
My code snippet for this looks like this:
Category.getProductOfCategory(productId, function(err, boughtProduct) {
if (err) {
res.send({
status: false,
data: err
})
} else {
// console.log('BoughtProduct: ', boughtProduct.products[0])
var bought = boughtProduct.products[0];
// console.log('theItem: ', bought.items.id(item._id));
bought.items.id(item._id).selldate = Date.now();
bought.save(function(err, results) {
if (err) {
res.send({
status: false,
data: err
})
} else {
// i is increased because we need it on line 5
// console.log('itemerr', err)
console.log('saved', results);
j++;
// the next() function is called when you
// want to move to the next item in the array
next();
}
});
}
});
But nothing is happening in the database. Im getting No errors but "results" is just undefined.
Can you please help me?
Update:
I have a solution BUT it works only on executing it once.. after that, its nothing happening again...
The Code:
Category.findById(catId, function (err, data) {
if (err) console.log(err);
data.products.id(productId).items.id(item._id).selldate = Date.now();
data.save(function (err, result) {
if (err) console.log(err);
j++;
next();
});
});
i have posted a sample program containing documents & sub-documents.
Kindly check this and let me know if you need additional information
Schema
const PostSchema = new Schema({
title : String
});
const HomeSchema = new Schema({
"name" : {
type : String,
required : true
},
"city" : {
type : String,
required : true
},
post : [PostSchema]
});
To Save document and subdocument
const cat = new HomeModel({
name: "tiger",
city : "africa",
post : [{
"title" : "tiger post"
}]
});
cat.save((user) => {
console.log("saved");
console.log(user);
})
.catch((err)=>{
console.log("err");
console.log(err);
});
To update document
HomeModel.update({name : "tiger"},{city : "china123"})
.then((home)=>{
console.log("updated");
console.log(home);
})
.catch((error) => {
console.log("error");
console.log(error);
});
To add new subdocument
HomeModel.findOne({name : "tiger"})
.then((home) => {
console.log("findone")
console.log(home);
home.post.push({"title" : "monkey"});
home.save();
})
.catch((err)=>{
console.log("error");
});
To update existing subdocument
method:1
HomeModel.findOne({name : "tiger"})
.then((home) => {
console.log("findone")
const tes=home.post.id("5a3fe65546c99208b8cc75b1");
tes.set({"title" : "it workssdfg"});
home.save();
})
.catch((err)=>{
console.log("error");
});
To find parent document using sub-document id
HomeModel.findOne({"post._id" : "5a3fe65546c99208b8cc75b1"})
.then((home) => {
console.log("findone")
console.log(home);
})
.catch((err)=>{
console.log("error");
});

Insert array into MongoDB subdocument with Node.js

I currently have a schema which looks as follows:
positionsApplied:[{
position_id:String,
index_position: Number
}],
I also have 3 objects which I need to insert into my database:
How can I insert these into my database through an Ajax call? What Ive tried so far:
Adding the data to an array like this:
["58d6b7e11e793c9a506ffe8f", 0, "58c2871414cd3d209abf4fc1", 1, "58d6b7e11e793c9a506ffe7f", 1]
Which would then be passed through my ajax call like this?(unsure)
$.ajax({
url: "/insertPositionIndex",
type: "POST",
dataType: "json",
data: {
newarray
},
success: function (data) {
console.log(data);
}
})
Inserting into the database is where I'm stuck, how do I break down the array in order to insert it?
app.post('/insertPositionIndex', function(req, res){
var object = req.body.ordered_divs;
console.log(req.body);
User.update(
{ "_id": req.user._id},
{ "$push":
{"positionsApplied":
{
// unsure what to do here?
}
}
}
).exec(function (err, result) {
console.log(result);
res.send({ results: result });
});
});
Any help is greatly appreciated!
* Note the position_id field in the schema is the div_id in the array, also the index-position field is the index_pos in the array.
user schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
id: String,
name: String,
companyname: String,
password: String,
email: String,
username: String,
location: String,
role:String,
teamwork:Number,
initiative:Number,
technical_skills: Number,
communication:Number,
employees: String,
profile_image: String,
biodescription: String,
twitter: String,
facebook: String,
instagram: String,
linkedin: String,
biodescription: String,
positionsApplied:[{
position_id:String,
index_position: Number
}],
experience: [{
title: String,
location: String,
company: String,
start: String,
end:String,
description:String
}],
position: [{
_id:String,
title: String,
location: String,
start: String,
term:Number,
description:String,
date: {type: Date, default: Date.now},
applied:[{
candidate_id: String,
profile_image: String,
location: String,
name: String,
_id:String
}],
}],
education: [{
school: String,
location: String,
degree: String,
start: String,
end:String,
description:String,
_id:String
}],
images: [{
one: String,
two: String,
three: String,
four: String,
five:String,
six:String
}],
});
module.exports = mongoose.model('User', User);
Since your Schema is an array of objects and the data that you are getting(as per console of the browser) is also an array of objects why don't you just pass that array itself(the one in the console of the browser) through ajax and use the $each of mongodb $push to save it into the database.
$.ajax({
url: "/insertPositionIndex",
type: "POST",
dataType: "json",
data: {
arrayOfObjects
},
success: function (data) {
console.log(data);
}
})
app.post('/insertPositionIndex', function(req, res){
var object = req.body.ordered_divs;
console.log(req.body);
User.update(
{ "_id": req.user._id},
{
"$push":
{
"positionsApplied":{
$each: req.body.arrayOfObjects
}
}
}
).exec(function (err, result) {
console.log(result);
res.send({ results: result });
});
});
You will have to change the arrayOfObjects keys to match that of your schema positionsApplied keys.

Mongoose query in MEAN stack

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?

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