Mongoose update and find object in multidimentional array - arrays

Im trying to get one of my user`s by the following query:
pokertable.findOne({ _id: gameid }, { "players.$.userid": userid })
but that wont execute. How come?
Im also looking for a way to update the user the same way, is that the same approatch?
Model:
pot_history: {
type: Array
},
players : [
{
userid: {
type: String,
default: 0,
},
username: {
type: String,
default: 'ukjent',
},
last_perform: {
type: Number,
default: 0,
},
cash: {
type: Number,
default: 0,
},
hands_history: {
type: Array,
},
}
],

For find use the query:
pokertable.findOne({ _id: gameid, "players.userid": userid });
And for update the same:
pokertable.update({ _id: gameid, "players.userid": userid }, {"players.$.userid": newUserid});

Related

Trending Posts Mongoose efficient way to do it?

How to do trending posts by views from a given day, month, etc and then make a data visualization in each post.
I thought about adding timestamps to each view but I don't know if it will be efficient and if it is the way to do something like this(If I would go with this solution, how much more space it would take in DB?).
Every time a user hits post URL, I add +1 to views and set a cookie to not add views on refresh by the same user. and then I save final to MongoDB.
for example how to achieve something like on NPM site with downloads data visualization
My Schema
const postsSchema = new mongoose.Schema({
title: String,
category: String,
shortDesc: String,
className: String,
description: String,
date: { type: Date, default: Date.now },
hidden: { type: Boolean, default: true },
nsfw: { type: Boolean, default: false },
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'App',
},
],
user: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
username: String,
country: String,
},
meta: {
downloads: {
type: Number,
default: 0,
},
fav: {
type: Number,
default: 0,
},
views: {
type: Number,
default: 0,
},
},
versions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Version',
},
],
lastUpdate: Date,
});

Add object to existing array in state

I have an application that uers lets create new tables, lets say I have the following state:
const initialState = {
table: [{
id: 1,
item: {}
}]
}
Now I want to add new objects to the item:
The reducer:
case types.ADD_ITEM:
return {
...state,
table: [...state.table, { item: action.item}],
loading: false
}
So after user adds new items in a table the state should look something like this:
table: [
// table with id 1
{
id: 1,
item: {
id: '1',
data: 'etc'
}
item: {
id: '2',
data: 'blabla'
}
},
// table with id 2
{
id: 2,
item: {
id: '1'
data: 'etc'
}
},
// etc
]
I think I have my reducer wrongly setup.. the tables are added correctly, but Items not.
Current format is:
table: [
{
id: 1,
item: []
},
{
item: {
id: '1'
}
}
]
I think you are trying to add the contents of action.item to your array. What you're currently doing is adding the contents as a new element. You can use the following to achieve your desired output:
case types.ADD_ITEM:
return {
...state,
table: [...state.table, { ...action.item }],
loading: false
}
Or if you want to get only the id field of the item, and store the item inside a item field:
case types.ADD_ITEM:
return {
...state,
table: [...state.table, { id: action.item.id, item: action.item }],
loading: false
}

Mongoose: Update by pushing an object in an array

This is the model I am working with:
name: {
type: String
},
payment: {
id: {
type: String,
required: true
},
cards: [
{
id: {
type: String
},
is_default: {
type: Boolean,
"default": false
}
}
]
}
I want to add a card to the cards array, for example:
card =
id: "some_token"
is_default: true
I am using the update method to push the card to the array, but it won't add the card to the document. Instead, it creates a new document with only those fields:
{
id: "some_token",
is_default: true,
_id: someId
}
Any idea how I can update the actual document I am targeting instead of creating a new document?
Here's my code (using CoffeeScript):
update_where =
payment:
id: "some_id"
update_push =
$push:
'payment.cards':
id: card_token
is_default: false
Customer.update update_where, update_push, {upsert: true}, (err, results) ->
# Do something with the results
Oh… I just noticed my mistake. The problem was in the where statement.
I was doing:
payment:
id: "some_id"
But the right thing to write is the following:
'payment.id': 'some_id'
And it now works!

Append to array nodejs mongodb

I am trying to append a string to an array that will be used to identify a user in multiple chatrooms. I have tried and can not get this to work. The log does not put out anything but:
[]
if (req.body.method == "setid") {
if(req.locals.user.chatid == null){
req.locals.user.chatid = {};
}
app.model.User.update(
{ _id: req.locals.user._id },
{ $addToSet: { chatid: [{mid: req.body.value}]} }
);
} else if (req.body.method == "checkid" && req.body.value) {
app.model.User.find({
"chatid": req.body.value
}, function(err, FoundUser) {
if (err || !FoundUser) {
res.end("ERROR");
} else {
console.log(FoundUser);
res.end(FoundUser[0].displayName);
}
});
}
Mongo Structure
{
email: { type: String, index: { unique: true }, required: true },
password: { type: String },
changeName: {type: Boolean},
displayName: { type: String, index: { unique: true }, required: true },
avatar: { type: String, default: '/assets/anon.png' },
permissions: {
chat: { type: Boolean, default: true },
admin: { type: Boolean, default: false }
},
online: { type: Boolean, default: true },
channel: { type: Types.ObjectId, ref: 'Channel', default: null }, //users channel
banned: { type: Boolean, default: false },
banend: {type:String, default: ''},
subs: [{ type: Types.ObjectId, ref: 'User' }],
about: { type: String },
temporary: {type: Boolean, default: false},
chatid:[{mid: {type:String}}]
}
Let's focus only on below snippet of code:
app.model.User.update(
{ _id: req.locals.user._id },
{ $addToSet: { chatid: [{mid: req.body.value}]} }
);
First, please verify whether you are getting a user in this query or not. Maybe, you are not getting the user at the first place and hence update won't work. Moreover, you will not get any error in this scenario.
Secondly, if you are getting the user then update your $addToSet query as: { $addToSet: { chatid: {mid: req.body.value}}}. These square brackets might cause an issue here.
Your query seems fine to me, which makes me doubt the parameters you are passing. Make sure that req.body.value is not null or undefined. In that case, the update won't happen and you will not get any error also!

Mongoose schema for storing an array of JSON objects for subdocuments

I have a JSON object that I want to create a schema for using mongoose
{ ProjectName: 'asdf',
Embargo: 'Yes',
Angle: '1',
Facts: '[{"count":1,"fact":"dsafdsaf","content":"dsafdsaf"}, {"count":3,"fact":"dsafdsaf","content":"dsafdsaf" } , {"count":2,"fact":"dsafdsaf","content":"dsafdsaf"}]',
About: '<p>Anthony Bodin </p>',
EditorNote: 'No',
OrderId: 'tok_14kGRO2Jju1nvjb47YF9jQTJ',
Payment: 'Paid' }
My problem is that the Facts element will contain and array of objects and I am not quite sure how to save it into the database as
Here is the schema that I have right now
var ArticleSchema = new mongoose.Schema({
userId: {
type: String,
default: ''
},
userEmail: {
type: String,
default: ''
},
article: {
date: {
type: Date,
default: Date()
},
ProjectName: {
type: String,
default: ''
},
Embargo: {
type: String,
default: true
},
Angle: {
type: String,
default: ''
},
Facts: {
type:Array
},
About: {
type:String,
default:''
},
EditorNote: {
type:String,
default:''
},
Payment: {
type: String,
default: 'Not Paid'
},
OrderId: {
type:String,
default:''
}
}
});
Is saving the data as an array the right way to save the Facts element ?
Its very simple. Just make facts an array.
So change
Facts: {
type:Array
},
to Facts: [] and it will be able to store the array of objects you have there in the Facts json field.

Resources