How to increment property's value(integer) inside .update() and $set mongoose? - arrays

I'm trying to find a document in my database using findOne() and then search that document for options array that contains objects. Then I check object's property if it's equal to pollOption then I want to increment that object's another property votes by 1, but I can't get that property's value so I can increment it. Please help.
Routes.js
router.post('/submitVote', function(req, res){
const {pollId, pollOption} = req.body;
Polls.findOne({_id: pollId}
).update({'options.option': pollOption}, {'$set': {
'options.$.votes': '', // INCREMENT BY 1 //
}}, function(err){
if(err){
return console.log(err);
} else {
return res.send('success');
}
});
});
Sample Model:
{
"_id": {
"$oid": "5b2ec4852a51d06734f71e79"
},
"options": [
{
"option": "Amazing!",
"votes": 0
},
{
"option": "Good.",
"votes": 0
}
],
"creator": "Guest",
"name": "Rate this website!",
"__v": 0
}
Polls.js - Schema
var mongoose = require('mongoose');
const Poll = new mongoose.Schema({
name: { type: String, required: true },
options: { type: Array, required: true },
creator: { type: String, default: 'Guest' }
});
const Polls = mongoose.model('Polls', Poll);
module.exports = Polls;

Related

Mongoose does not update my array in the database

I'm trying to update my collection with mongoose.
This is my Schema:
var FamilySchema = mongoose.Schema({
construction: {
type: Array,
default: [
["foundry", 0],
["farm", 0],
["sawmill", 0]
]
}
});
And this is my code:
app.put('/construction/updateConstruction/:id', (req, res) => {
let id = req.params.id;
Family.findById(id, (err, familiaDB) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
}
if (!familiaDB) {
return res.status(400).json({
ok: false,
err
});
}
// I want to update the value of the posicion 0 in the array.
familiaDB.construction[0][1] = 1;
familiaDB.save();
console.log(familiaDB);
});
});
Result in console.log after making the request:
Escuchando puerto: 3000
Base de datos ONLINE
{ state: true,
construction:
[ [ 'foundry', 1 ],
[ 'farm', 0 ],
[ 'sawmill', 0 ],
_id: 5bb8d69c604625211c572ada,
__v: 0 }
In console.log everything is fine and updated, but in my db it is not updated. I have checked it many times in robomongo and never updates it.
The quickest way to do this would be with findOneAndUpdate:
Family.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId("YOURID") },
{ $set: { 'construction.0.1': 'YourValue' }}
)
This will do it in one statement.
Now instead of doing this by index you can do it with $elemMatch and update the correct one via:
Family.findOneAndUpdate(
{_id: ObjectId("YOURID"), 'cons': { $elemMatch: { '0': 'foundry' }}},
{ $set: { 'cons.$.1': 'YourValue' } }
)

Mongoose Update array in a document does not work as expected

I'm scratching my head since a couple day on how to update the content of an array with Mongoose.
Here is my schema to begin with:
const playedGameSchema = new Schema ({
created: Date,
updated: Date,
game: {
type: Schema.Types.ObjectId,
ref: 'game'
},
creator: {
id: {
type: Schema.Types.ObjectId,
ref: 'user'
},
score: Number
},
partners: [{
id: {
type: Schema.Types.ObjectId,
ref: 'user'
},
score: Number
}]
});
module.exports = mongoose.model('PlayedGame', playedGameSchema);
Basically, what I want to achieve is to, at the same time:
- Update the creator.score (successful with dot notation).
- Update the score key for each partner (unsuccessful).
Here is the result of a document created:
{
"creator": {
"id": "5b8544fa11235d9f02a9b4f1",
"score": 0
},
"_id": "5bb6375f5f68cc5c52bc93ae",
"game": "5b45080bb1806be939bfde03",
"partners": [
{
"_id": "5bb637605f68cc5cafbc93b0",
"id": "5b85497111235d677ba9b4f2",
"score": 0
},
{
"_id": "5bb637605f68ccc70ebc93af",
"id": "5b85497111235d677ba9b4f2",
"score": 0
}
],
"created": "2018-10-04T15:53:03.386Z",
"updated": "2018-10-04T15:53:03.386Z",
"__v": 0
}
As I said, I was able to change the score of the score creator by passing something like { "creator.score": 500 } as a second parameter, then I switch to trying to update the array.
Here is my lambda function to update the score for each partner:
export const update: Handler = (event: APIGatewayEvent, context: Context, cb: Callback) => {
context.callbackWaitsForEmptyEventLoop = false;
const body = JSON.parse(event.body);
let partnersScore: object = {};
if(body.update.partners) {
body.update.partners.forEach((score, index) => {
const key = `partners.${index}.$.score`;
partnersScore = Object.assign(partnersScore, { [key]: score});
console.log(partnersScore);
});
}
connectToDatabase().then(() => {
console.log('connected', partnersScore)
PlayedGame.findByIdAndUpdate(body.id, { $set: { partners: partnersScore } },{ new: true})
.then(game => cb(null, {
statusCode: 200,
headers: defaultResponseHeader,
body: JSON.stringify(game)
}))
.catch(err => {
cb(null, {
statusCode: err.statusCode || 500,
headers: { 'Content-Type': 'text/plain' },
body: err
})});
});
}
Which passes a nice { 'partners.0.$.score': 500, 'partners.1.$.score': 1000 } to the $set.
Unfortunately, the result to my request is a partners array that contains only one empty object.
{
"creator": {
"id": "5b8544fa11235d9f02a9b4f1",
"score": 0
},
"_id": "5bb6375f5f68cc5c52bc93ae",
"game": "5b45080bb1806be939bfde03",
"partners": [
{
"_id": "5bb63775f6d99b7b76443741"
}
],
"created": "2018-10-04T15:53:03.386Z",
"updated": "2018-10-04T15:53:03.386Z",
"__v": 0
}
Can anyone guide me into updating the creator score and all partners score at the same time?
My thoughs about findOneAndUpdate method on a model is that it's better because it doesn't require the data to be changed outside of the BDD, but wanting to update array keys and another key seems very difficult.
Instead, I relied on a set/save logic, like this:
PlayedGame.findById(body.id)
.then(game => {
game.set('creator.score', update.creatorScore);
update.partners.forEach((score, index) => game.set(`partners.${index}.score`, score));
game.save()
.then(result => {
cb(null, {
statusCode: 200,
headers: defaultResponseHeader,
body: JSON.stringify(result)
})
})
.catch(err => {
cb(null, {
statusCode: err.statusCode || 500,
headers: { 'Content-Type': 'text/plain' },
body: JSON.stringify({ 'Update failed: ': err })
})});
})

Can't Store Nested JSON Array to MongoDB Using Mongoose

I have JSON on Postman like this:
{
"hostname": [
{
"item": [
{
"system": "10l313",
"severity": "2"
},
{
"system": "2131414",
"severity": "3"
}
]
},
{
"item": [
{
"system": "4234235",
"severity": "4"
}
]
}
]
}
I want to create new collections in mongodb from json above. It's just a little picture of the actual json array, the above json array can contain an enormous array. I am confused how to save as many json arrays using mongoose, do i have to loop as much as array length or is there other easier way?
mongoose schema:
var ItemSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
system: {
type: String
},
severity: {
type: Number
}
})
var VulnSchema = new Schema({
hostname: [{
item: [{ItemSchema}]
}]
});
controller:
exports.create_vulnerabilities = function (req, res) {
var vuln = new Vuln ({
_idFIle: mongoose.Types.ObjectId(),
hostname: req.body.hostname
});
vuln.save()
.then(result => {
res.status(201).json({
result
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
I have tried running my code but the result is like this. The problem is system and severity attribute are not stored in mongodb.
{
"_id" : ObjectId("5b4c39a301651a0fc047bec7"),
"hostname" : [
{
"_id" : ObjectId("5b4c39a301651a0fc047beca"),
"item" : [
{
"_id" : ObjectId("5b4c39a301651a0fc047becc")
},
{
"_id" : ObjectId("5b4c39a301651a0fc047becb")
}
]
},
{
"_id" : ObjectId("5b4c39a301651a0fc047bec8"),
"item" : [
{
"_id" : ObjectId("5b4c39a301651a0fc047bec9")
}
]
}
],
"__v" : 0
}
Please help me. thank you
Change
var VulnSchema = new Schema({
hostname: [{
item: [{ItemSchema}]
}]
});
to
var VulnSchema = new Schema({
hostname: [{
item: [ItemSchema]
}]
});
Example try running this:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema,ObjectId = Schema.ObjectId;
var ItemSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
system: {
type: String
},
severity: {
type: Number
}
})
var VulnSchema = new Schema({
hostname: [{
item: [ItemSchema]
}]
});
const Vuln = mongoose.model('Vuln', VulnSchema);
var hostname = [
{
"item": [
{
"system": "10l313",
"severity": "2"
},
{
"system": "2131414",
"severity": "3"
}
]
},
{
"item": [
{
"system": "4234235",
"severity": "4"
}
]
}
]
var vuln = new Vuln ({
_idFIle: mongoose.Types.ObjectId(),
hostname: hostname
});
vuln.save()
.then(result => {
console.log(JSON.stringify(result))
})
.catch(err => {
console.log(err);}
);

MongoDb unable to populate user

Hi I am trying to populate user into another schema called feedbackschema.
Feedback schema
const mongoose = require('mongoose');
const {
Schema,
} = mongoose;
// Create Schema
const FeedbackSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
pro: {
type: String,
required: true,
},
con: {
type: String,
required: true,
},
comments: {
type: String,
required: true,
},
rating: {
type: String,
required: true,
},
});
// Create model
const feedback = mongoose.model('feedbacks', FeedbackSchema);
module.exports = feedback;
User Schema
const mongoose = require('mongoose');
const {
Schema,
} = mongoose;
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
},
password: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
});
// Create a model
const user = mongoose.model('users', UserSchema);
// Export the model
module.exports = user;
and here is my controller where I am trying to populate the user
getAllFeedbacks: async (req, res) => {
const errors = {};
try {
const feedbacks = await Feedback.find().populate('user');
return res.json(feedbacks);
} catch (err) {
errors.noFeedbacks = 'Please try again';
return res.status(404).json(errors);
}
},
Json I am receiving through postman is this
[
{
"_id": "5b3adf88f3c4cd836bdc2eda",
"pro": "knfklngfdklgnfdgknkln",
"con": "Sales executive updates",
"comments": "This is a another funfact for me is me too",
"rating": "8",
"__v": 0
}
]
It is supposed to show user key but somehow its not working. I checked the current user data is already there but for some reason its not pushing the user info feedback object.
FeedBack collection
[
{
"_id": {
"$oid": "5b3adf88f3c4cd836bdc2eda"
},
"pro": "knfklngfdklgnfdgknkln",
"con": "Sales executive updates",
"comments": "This is a another funfact for me is me too",
"rating": "8",
"__v": 0
}
]
User Collection
[
{
"_id": {
"$oid": "5b37e456565971258da97d5e"
},
"isAdmin": false,
"name": "montygoldy",
"email": "montygoldy#gmail.com",
"password": "$2a$10$zWbxV0Q3VPUxRC6lzJyPBec3P/8zYBaSCTJ2n88Uru3zzFlicR2rq",
"__v": 0
}
]

How to remove Object from array using mongoose

I'm trying to remove an object from an array in a document using mongoose.
The Schema is the following:
var diveSchema = new Schema({
//irrelevant fields
divers: [{
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
meetingLocation: { type: String, enum: ['carpool', 'onSite'], required: true },
dives: Number,
exercise: { type: Schema.Types.ObjectId, ref: 'Exercise' },
}]
});
a possible entry can be
{
//irrelevant fields
"divers": [
{
"_id": "012345678",
"user": "123456789",
"meetingLocation": "carpool",
"exercise": "34567890",
},
{
"_id": "012345679",
"user": "123456780",
"meetingLocation": "onSite",
"exercise": "34567890",
}
]
}
Say I want to remove the entry where user is 123456789 (note I do not know the _id at this point).
How do I do this correctly?
I tried the following:
var diveId = "myDiveId";
var userIdToRemove = "123456789"
Dive.findOne({ _id: diveId }).then(function(dive) {
dive.divers.pull({ user: userIdToRemove });
dive.save().then(function(dive) {
//do something smart
});
});
This yieled no change in the document.
I also tried
Dive.update({ _id: diveId }, { "$pull": { "divers": { "diver._id": new ObjectId(userIdToRemove) } } }, { safe: true }, function(err, obj) {
//do something smart
});
With this I got as result that the entire divers array was emptied for the given dive.
What about this?
Dive.update({ _id: diveId }, { "$pull": { "divers": { "user": userIdToRemove } }}, { safe: true, multi:true }, function(err, obj) {
//do something smart
});
I solve this problem using this code-
await Album.findOneAndUpdate(
{ _id: albumId },
{ $pull: { images: { _id: imageId } } },
{ safe: true, multi: false }
);
return res.status(200).json({ message: "Album Deleted Successfully" });
Try this
Dive.update({ _id: diveId },{"$pull": { "drivers": {"user": "123456789"}}})
Try this async code
var diveId = "myDiveId";
var userIdToRemove = "123456789"
const dive=await Dive.findOne({ _id: diveId })
await dive.divers.pull({ user: userIdToRemove });
await dive.save();
Use this with try/catch:
await Group.updateOne(
{ _id: groupId },
{ $pull: { members: {id: memberId }}}
);

Resources