nodejs mongoose push to an array inside schema [duplicate] - arrays

This question already has answers here:
pushing object into array schema in Mongoose
(2 answers)
Closed 5 years ago.
I have a mongoose schema inbox-model:
var schema = mongoose.Schema({
email: String,
data: [{
from: String,
to: String,
msg: String
}]
})
var Inbox = module.exports = mongoose.model('Inbox',schema);
module.exports.addData = function(inbox, callBack){
inbox.save(callBack);
}
I need to add to data[] array for a specific email when there's new data for that email address.
I can add data this way, through my router by calling:
var Inbox = require('inbox-model');
var inbox = new Inbox({
email: 'some#email.com',
data:[{
from: 'from',
to: 'to',
msg: 'msg'
})
Inbox.addData(inbox, Inbox);
though it doesn't add to data[] but keeps adding a whole row.
Help is much appreciated, I've searched for similar questions, but I couldn't find on adding data, just creating models with arrays.

This question has been answered a lot of time on StackOverflow. However, I'm answering it again
// Schema File - userSchema.js
const userSchema = new Schema({
email: { type: String, required: true },
data: [{
from: String,
to: String,
msg: String
}]
})
const user = mongoose.model('user', userSchema)
module.exports = user
// Service File
const user = require('./userSchema')
function someFunction(email, from, to, message) {
user.findOne({ email: email }, function(err, document) {
if (document) {
document.data.push({
from: from,
to: to,
msg: message
})
document.save(function(err) {
err != null ? console.log(err) : console.log('Data updated')
})
}
})
}

Related

Mongo schema, array of string with unique values

I'm creating the schema for a mongo document and I can do everything except prevent duplicates in a non-object array.
I'm aware of the addToSet, but I'm referring to Mongo Schema.
I don't want to check on Update using $addToSet, rather I want this to be part of my schema validation.
Example below.
let sampleSchema = {
name: { type: 'String', unique: true },
tags: [{ type: 'String', unique: true }]
}
The above snippet prevents name from having duplicate values. It allows tags to be stored as a string array.
But.. I cannot limit the array to be unique strings.
{ name: 'fail scenario', tags: ['bad', 'bad', 'array']}
I'm able to insert this record which should be a fail scenario.
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const _ = require('underscore');
let sampleSchema = new mongoose.Schema({
name: {
type: 'String',
unique: true
},
tags: [{
type: 'String'
}]
})
sampleSchema.pre('save', function (next) {
this.tags = _.uniq(this.tags);
next();
});
const Sample = mongoose.model('sample', sampleSchema, 'samples');
router.post('/sample', function (req, res, next) {
const sample = new Sample(req.body);
sample.save()
.then((sample) => {
return res.send(sample);
})
.catch(err => {
return res.status(500).send(err.message);
})
});
I've come to the conclusion that this is impossible to do via Mongoose Schema.
JSON schema is done like so.
let schema = {
name: { type: 'string' }
tags: {
type: 'array',
items: { type: 'string', uniqueItems: true }
}
}
I'll validate with JSON schema before creating Mongo Document.
This method builds on Med's answer, handles references, and done completely in scheme validation.
let sampleSchema = new mongoose.Schema({
strings: [{type: 'String'}],
references: [{type: mongoose.Schema.Types.ObjectId, ref: 'Reference'],
});
sampleSchema.pre('save', function (next) {
let sample = this;
sample.strings = _.uniq(sample.strings, function(i) {return (i._id) ? i._id.toString() : i;});
sample.references = _.uniq(sample.references, function(i) {return (i._id) ? i._id.toString() : i;});
return next();
});
I'm a little late, but maybe this will help someone in the future.
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
},
reference: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'SomeOtherSchema',
// Add a custom validator.
validate: {
// The actual validator function goes here.
// "arr" will be the value that's being validated (so an array of
// mongoose new ObjectId statements, in this case).
validator: arr => {
// Convert all of the items in the array "arr", to their string
// representations.
// Then, use those strings to create a Set (which only stores unique
// values).
const s = new Set(arr.map(String));
// Compare the Set and Array's sizes, to see if there were any
// duplicates. If they're not equal, there was a duplicate, and
// validation will fail.
return s.size === arr.length;
},
// Provide a more meaningful error message.
message: p => `The values provided for '${ p.path }', ` +
`[${ p.value }], contains duplicates.`,
}
},
});
The above commented code should be pretty self explanatory.
With the newer version(s) of MongoDB, you can use $addToSet to append to an array if and only if the new value is unique compared to the items of the array.
Here's the reference: https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/
Here's an example:
const SampleSchema = new mongoose.Schema({
tags: [String]
});
const Sample = mongoose.model('Sample', SampleSchema);
// append to array only if value is unique
Sample.findByIdAndUpdate({_id: 1, {$addToSet: {tags: "New Tag"}}});
This will effectively update the tags if the "New Tag" is not already present in the tags array. Otherwise, no operation is done.

NodeJS & Mongoose: Add element to existing empty array

I am building a NodeJS application for creating reports based on data from a MSQL database. All application relevant data is stored in a MongoDB using Mongoose. My mongoose model contains an empty array which is then filled by the user via a Rest-API.
I get an error when adding a new element to the array. I already tried it with model.array.push(object); model.save() and findByIdAndUpdate(...). Find my code including the two different attempts below:
Mongoose schema
var sqlSchema = mongoose.Schema({ // Schema to store information about SQL-procedures
'name': String,
'inputs': [
{
'name': String,
'type': String,
'value': String,
'adjustable': Boolean
}
]
});
REST API
My application accepts new elements for the 'inputs'-array via POST:
var mongoose = require('mongoose'),
SqlProcedure = mongoose.model('SqlProcedure');
// ...
router.post('/sql/:id/inputs', function(req, res) {
SqlProcedure.findById(req.params.id, function(err, sql) {
if(err) {
res.send(msg.error('error retrieving sql-procedure', err));
} else {
if(sql.inputs.length > 0) { // catch empty array
for(var key in sql.inputs) {
if(sql.inputs[key].name == req.body.name) {
return res.send(msg.error('input already in inputs', err));
}
}
}
var data = req.body;
var input = {
name: data.name,
type: data.type,
value: data.value,
adjustable: data.adjustable
};
// attempt one or two
}
});
});
attempt one:
sql.inputs.push(input); // EXCEPTION 1
sql.save(function(err) {
// fancy errorhandling
return res.send(msg.ok(sql));
});
attempt two:
SqlProcedure.findByIdAndUpdate(req.params.id,
{$push: {inputs: input}}, // EXCEPTION 2
{safe: true, upsert: true},
function(err, sql) {
// fancy errorhandling
res.send(msg.ok('input added to sql-procedure' + req.params.id));
}
);
Exceptions
Attempt one:
throw new CastError('string', value, this.path);
^
Error
at MongooseError.CastError (\node_modules\mongoose\lib\error\cast.js:18:16)
at SchemaString.cast (\node_modules\mongoose\lib\schema\string.js:434:9)
at Array.MongooseArray.mixin._cast (\node_modules\mongoose\lib\types\array.js:124:32)
at Array.MongooseArray.mixin._mapCast (\node_modules\mongoose\lib\types\array.js:295:17)
at Object.map (native)
at Array.MongooseArray.mixin.push (\node_modules\mongoose\lib\types\array.js:308:25)
at Query.<anonymous> (\app\api\sql_procedure.js:69:28)
at \node_modules\mongoose\node_modules\kareem\index.js:177:19
at \node_modules\mongoose\node_modules\kareem\index.js:109:16
at doNTCallback0 (node.js:417:9)
at process._tickCallback (node.js:346:13)
Attempt two:
"stack": "Error
at MongooseError.CastError (\\node_modules\\mongoose\\lib\\error\\cast.js:18:16)
at SchemaArray.cast (\\node_modules\\mongoose\\lib\\schema\\array.js:156:15)
at SchemaArray.cast (\\node_modules\\mongoose\\lib\\schema\\array.js:167:17)
at Query._castUpdateVal (\\node_modules\\mongoose\\lib\\query.js:2384:22)
at Query._walkUpdatePath (\\node_modules\\mongoose\\lib\\query.js:2298:27)
at Query._castUpdate (\\node_modules\\mongoose\\lib\\query.js:2227:23)
at castDoc (\\node_modules\\mongoose\\lib\\query.js:2430:18)
at Query._findAndModify (\\node_modules\\mongoose\\lib\\query.js:1752:17)
at Query._findOneAndUpdate (\\node_modules\\mongoose\\lib\\query.js:1620:8)
at \\ITZReport\\node_modules\\mongoose\\node_modules\\kareem\\index.js:156:8
at \\node_modules\\mongoose\\node_modules\\kareem\\index.js:18:7
at doNTCallback0 (node.js:417:9)\n at process._tickCallback (node.js:346:13)",
"message": "Cast to undefined failed for value \"[object Object]\" at path \"inputs\"",
"name": "CastError",
"value": [
{
"adjustable": "true",
"value": "Harry Potter",
"type": "String",
"name": "salesman"
}
],
"path": "inputs"
data to be inserted
{ name: 'salesman',
type: 'String',
value: 'Harry Potter',
adjustable: 'true' }
I am new to NodeJS and mongoose and tried to solve this on my own for many hours. It would be great if anyone out there could help me!
Thanks in advance,
dj2bee
Update
I think I should clarify the process of the user interacting with the REST-API:
The user creates a new record by passing over the value for the
name. At this point the name is set and the inputs-array
is empty.
In the next step, the user adds new records to the
inputs-array one by one. The name stays as it is and only
new inputs are added to the array.
The user should be able to edit or remove entries from the
inputs-array.
Changing the data-type of adjustable to String did not made any changes. I also tried hard coding attributes and not passing them via HTTP-POST - still the same exception.
After hours of searching the web and testing the weirdest things in my code I found the solution:
You can't name a field 'type' in the mongoose-schema. That's it.
The correct code looks like this:
Mongoose schema
var sqlSchema = mongoose.Schema({
'name': String,
'inputs': {
'name': String,
'datatype': String, // you can't name this field 'type'
'value': String,
'adjustable': Boolean
}
});
REST API
router.post('/sql/:id/inputs', function(req, res) {
SqlProcedure.findById(req.params.id, function(err, sql) {
if(err) {
res.send(msg.error('error retrieving sql-procedure', err));
} else {
if(!sql) {
return res.send(msg.error('no sql-procedure found with id '
+ req.params.id, null));
}
// check for duplicates
var data = req.body;
var input = {
'name': data.name,
'datatype': data.type,
'value': data.value,
'adjustable': data.adjustable
};
SqlProcedure.findByIdAndUpdate(req.params.id,
{$push: {inputs: input}},
{safe: true, upsert: true},
function(err, sql) {
// fancy error handling
}
);
}
});
});
You should make your data to be inserted as
{ name: 'salesman',
inputs: [{name: 'salesman',
type: 'String',
value: 'Harry Potter',
adjustable: true}]}
i.e. true without quotes and inputs as an array
or else in schema make adjustable as String and remove input as array in model definition
var sqlSchema = mongoose.Schema({ // Schema to store information about SQL-procedures
'name': String,
'type': String,
'value': String,
'adjustable': String
});

Allow users to add items to their profiles Mongoose

I am building a mean stack app with express and mongoose. I have two schemas, userSchema and courseSchema:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var courseSchema = mongoose.Schema({
title:{type:String, required:'{PATH} is required!'},
featured:{type:Boolean, required:'{PATH} is required!'},
published:{type:Date, required:'{PATH} is required!'},
courseLink:{type:String, required:'{PATH} is required!'},
user: [{type:Schema.Types.ObjectId, ref : 'User'}]
});
var Course = mongoose.model('Course', courseSchema);
module.exports = Course;
var userSchema = mongoose.Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
username: {
type: String,
required: true,
unique: true // creates unique index inside MongoDB
},
salt: {type: String, required: true},
hashed_pwd: {type: String, required: true},
roles:[String],
courses:[{type: Schema.ObjectId,
ref: 'Course' }]
});
I am able to create users and and courses (as an admin). What I want to do now is to allow each user add a course to his list of courses (or just click a 'like' button beside the course and that course would be added to his profile).
On the side of the controller, I have tried to check for the user id from the session, find that user and add the course to his document. But that's where I am stuck,
exports.addMyCourse = function(req, res){
console.log('user id', req.session.passport.user);
console.log('id', req.body._id);
var currentUserId = req.session.passport.user;
User.findOne({'_id':currentUserId}, function(err, doc){
console.log(doc);
});
Most of the solutions I looked at are not very clear about this. Any help would be appreciated.
RESOLVED:
I used $addToSet to add the course objects into the courses array inside the User model:
This might be useful for people searching for similar soutions:
My User schema:
var userSchema = mongoose.Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
username: {
type: String,
required: true,
unique: true // creates unique index inside MongoDB
},
salt: {type: String, required: true},
hashed_pwd: {type: String, required: true},
roles:[String],
courses:[{
type:Schema.ObjectId, ref:'Course'
}]
});
var User = mongoose.model('User', userSchema);
My Course schema:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var courseSchema = mongoose.Schema({
title:{type:String, required:'{PATH} is required!'},
featured:{type:Boolean, required:'{PATH} is required!'},
published:{type:Date, required:'{PATH} is required!'},
courseLink:{type:String, required:'{PATH} is required!'}
});
var Course = mongoose.model('Course', courseSchema);
Inside my controllers folder, I have users.js and courses.js:
In the courses.js file, I created the addMyCourses middleware to update the User model's courses array by first retrieving the current user's id from the session and using $addToSet to insert the object and avoid duplicates at the same time. Also I made sure I am adding only the ObjectId's of the courses and not the entire course document so I won't have future problems with too much data in one document:
exports.addMyCourse = function(req, res){
var myCourse = {
title: req.body.title,
featured: req.body.featured,
published: req.body.published,
courseLink: req.body.courseLink
};
var currentUserId = req.session.passport.user;
var courseId = req.body._id;
User.update({_id:currentUserId},
{$addToSet: {"courses": courseId}},
{safe: true, upsert: true, new : true},
function(err, model) {
console.log(model);
}
);
};
Since I only had the ObjectId's of the courses inside the courses array of the User model, I had to use mongoose's populate() method to do a joint query on both models so that I get the corresponding course documents of the ids.
In users.js file:
exports.getUserCourses = function(req, res, next){
var currentUserId = req.session.passport.user;
User.findById(currentUserId).populate('courses')
.exec(function(err, data){
if(err) {
console.log(err);
}
console.log('user courses', data);
res.send(data);
})
};

location object expected, location array not in correct format

I have spent doing such a straight forward thing. I just want to do a CRUD operation on a user model using nodejs, mongoose, restify stack. My mongo instance is on mongolab.
The user should contain a "loc" field . User schema is as follows :
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var userSchema = new Schema( {
email_id : { type: String, unique: true },
password: { type: String},
first_name: String,
last_name: String,
age: String,
phone_number: String,
profile_picture: String,
loc: {
type: {},
coordinates: [Number]
}
});
userSchema.index({loc:'2d'});
var User = mongoose.model('user', userSchema);
module.exports = User;
the rest api used to post is as follows :
create_user : function (req, res, next) {
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.latitude;
var user = new User(
{
email_id : req.params.email_id,
password: req.params.password,
first_name: req.params.first_name,
last_name: req.params.last_name,
age: req.params.age,
phone_number: req.params.phone_number,
profile_picture: req.params.profile_picture,
loc: {
type:"Point",
coordinates: [1.0,2.0] // hardcoded just for demo
}
}
);
user.save(function(err){
if (err) {
res.send({'error' : err});
}
res.send(user);
});
return next();
},
Now when i do a POST call on curl -X POST http://localhost:3000/user --data "email_id=sdass#dfAadsfds&last_name=dass&age=28&phone_number=123456789&profile_picture=www.jakljf.com&longitude=1.0&latitude=2.0"
I get the following error
{
error: {
code: 16804
index: 0
errmsg: "insertDocument :: caused by :: 16804 location object expected, location array not in correct format"
op: {
email_id: "sdass#dfAadsfdsadkjhfasvadsS.com"
password: "sdass123DadakjhdfsfadfSF45"
first_name: "shaun"
last_name: "dass"
age: "28"
phone_number: "123456789"
profile_picture: "www.jakljf.com"
loc: {
coordinates: [2]
0: 1
1: 2
-
type: "Point"
}-
_id: "55efc95e0e4556191cd36e5e"
__v: 0
}-
}-
}
The location field is giving problems as the POST call works just fine if i remove the loc field from model
Below are the hits/trials I did :
1) Change userSchema.index({loc:'2d'}); to userSchema.index({loc:'2dsphere'});
2) Changing loc schema to everything given in Stackoverflow. I would like to know the right way to define this though.
3) Passing the hardcode 2d array but still it says Location object expected, location array not in correct format" what format is required for this ?
Any help in this regard is greatly appreciated. Thanks.
MongoDB 2d index requires the legacy coordinates pairs format, which is just an array of coordinates like [1, 2].
If you need GeoJSON support, please use the 2dsphere index.
userSchema.index({loc:'2dsphere'});
If you are using Spring Boot make sure you set the index type to 2DSphere:
#GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE) GeoJsonPoint location;

How to query mongoose by property that is and array item

I have a mongoose model that looks like this:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var PictureSchema = new Schema({
listId: { type: Array, required: true },
thumb: { type: String, required: true },
large: { type: String, required: true }
});
var Picture = module.exports = mongoose.model('Picture', PictureSchema);
I am trying to update instances of this model in my router by looking up a Picture via the "listId" property. Like this:
app.put('/pictures/append', function(req, res) {
var targetListId = req.body.targetListId
, currentListId = req.body.currentListId;
Picture
.find({ listId: currentListId }, function (err, picture) {
console.log('found pic', picture);
picture.listId.push(targetListId);
picture.save(function(err, pic) {
console.log('pic SAVED', pic);
});
});
});
"currentListId" is a string, and listId is an array of currentListId's. Maybe this isn't the correct way to query a a property that is an array?
I am getting an error:
TypeError: Cannot call method 'push' of undefined
On the line:
picture.listId.push(targetListId);
But when I look up the picture models in mongo, they DO have listId arrays and some DO contain the item "currentListId" that I am using for my query.
I tried using $elemMatch and $in but I don't know if I was using them correctly.
Any idea if I am just writing my query wrong?
Specifying an Array typed field in your schema is equivalent to Mixed which tells Mongoose that field could contain anything. Instead, change your schema to something like this:
var PictureSchema = new Schema({
listId: [String],
thumb: { type: String, required: true },
large: { type: String, required: true }
});

Resources