I am trying to edit a discord bot made in python (I stored data initially in python) and transferring it to javascript (node.js) and can't feature out while connecting to my old db why findOne giving me null while providing proper discord id.
Without anything inside
Code
anifarm.findOne();
Output
{
_id: 707876147324518400,
farmed: 17,
ordered: 5,
pimage: 'https://media.tenor.com/images/e830217a5d9926788ef25119955edc7f/tenor.gif',
pstatus: 'I want you to be happy. I want you to laugh a lot. I don’t know what exactly I’ll be able to do for you, but I’ll always be by your side.',
avg: 184,
speed: 2,
badges: [
'https://cdn.discordapp.com/attachments/856137319149207563/856137435696332800/Black-and-Yellow-Gaming-Badge--unscreen.gif',
'https://cdn.discordapp.com/attachments/856137319149207563/862219383866523688/Front-removebg-preview.png', 'https://cdn.discordapp.com/attachments/856137319149207563/862240758768599100/download-removebg-preview.png'
],
setBadges: 'https://cdn.discordapp.com/attachments/856137319149207563/862240758768599100/download-removebg-preview.png'
}
With id inside
Code
anifarm.findOne({
_id: 707876147324518400
});
Output
null
anifarm in the schema.
Decleared Schema
module.exports = mongoose.model('anifarm', new mongoose.Schema({
_id: Number,
farmed: {
type: Number,
default: 0
},
ordered: {
type: Number,
default: 0
},
pimage: {
type: String,
default: ""
},
pstatus: {
type: String,
default: ""
},
avg: {
type: Number,
default: 200
},
speed: {
type: Number,
default: 2
},
badges: {
type: Array,
default: []
},
setBadges: {
type: String,
default: ""
}
},
{
collection: 'anifarm',
versionKey: false
})
);
I cannot figure out what am I doing wrong. This problem also happens with .find()
Nothing inside find fetches everything by if I provide id it sends a empty array.
A Little help would be appreciated
For you problem use mongoose-long that should fix your problem.
This library will handle all long type data for mongoose since mongoose cannot handle long type data
you can't pass an id as a number, you will have to use ObjectId to convert the id to an instanceof ObjectId
Change your code like this
anifarm.findOne({
_id: mongoose.Types.ObjectId(707876147324518400);
});
If you're querying by _id, use findById() instead.
anifarm.findById("707876147324518400")
Official docs here
Related
I know that this question might be beginner level but I haven't find anything yet.
I would like to update an array of objects with mongoose. I am interested in updating one object from the users array according to the index.
Usually one user is getting changed at a time.
Here is my schema:
_id: Schema.Types.ObjectId,
name: { type: String, required: true },
gm: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
users: [],
I want to update an object in the users array which is like this:
{
id:"5bcb7c7ff9c5c01b9482d244",
gm:"5bcb7c7ff9c5c01b9482d246",
name:"room 1"
users: [
{
id:"5bcb7c7ff9c5c01b9482d243",
stats:{
power:10,
mobility: 5,
vitality: 20
},
bag:{itemSlot1: "Knife",itemSlot2:"Sword" }
},
{
id:"5bcb7c7ff9c5c01b9482d241",
stats:{
power:10,
mobility: 5,
vitality: 20
},
bag:{itemSlot1: "Knife",itemSlot2:"Sword" }
]
}
I want to perform a patch or a post request to update one user each time from the user array. i am getting the id of the user from req.body to match it with my db.
My request is like this:
I would like to update based on a request like this:
data = {
stats={
power:"10",
vitality:"20"
}
}
Thanks in advance,
Cheers
You can do an update like this:
YourSchema.update({
'users.id': '5bcb7c7ff9c5c01b9482d243'
}, {
$set: {
'users.$.stats': data.stats
}
})
Which would update the first user with id 5bcb7c7ff9c5c01b9482d243 power stats to 20
This is using the update with the $ positional operator to update the element in the array.
Just have it set up in your post/patch request.
In the Numeric Model for storing monetary values, the MongoDB docs state:
From the mongo shell decimal values are assigned and queried using the NumberDecimal() constructor.
Similarly, when using the Morphia Java library, BigDecimals are automatically inserted as BigDecimals.
I'm querying Mongo in Node with Mongoose and attempting to extract the numeric value of a field stored as a NumberDecimal. However, the value is oddly wrapped in query results and I'm not sure how to extract it through Mongo or Mongoose:
[
{
"openValue":{
"$numberDecimal":"119.931"
},
"timestamp":"2017-01-20T10:30:00.000Z"
},
{
"openValue":{
"$numberDecimal":"119.965"
},
"timestamp":"2017-01-20T10:31:00.000Z"
}
]
One post I read stated using parseFloat() in my application code will perform what I desire, however it's not efficient to iterate through the result to perform this transformation. Avoiding iterating and transforming would mean running the function on the NumberDecimals whenever I want their value every time, which would be annoying.
Is there a way I can use Mongo or Mongoose to convert the above JSON query-result into what's below?
[
{
"openValue": 119.931,
"timestamp":"2017-01-20T10:30:00.000Z"
},
{
"openValue": 119.965,
"timestamp":"2017-01-20T10:31:00.000Z"
},
{
"openValue": 119.975,
"timestamp":"2017-01-20T10:32:00.000Z"
}
]
I tried selecting the field as ...openValue.$numberDecimal, but this didn't work. Thank you!
Edit: Here's my Mongoose schema:
var EquityHistoryModel = new Schema({
_id: {
equityIdentifier: { type: {
exchange: { type: String, index: true },
symbol: { type: String, index: true }
}, index: true },
instant: { type: Date, index: true },
durationMinutes: { type: Number }
},
open: { type: mongoose.Schema.Types.Decimal },
high: { type: mongoose.Schema.Types.Decimal },
low: { type: mongoose.Schema.Types.Decimal },
close: { type: mongoose.Schema.Types.Decimal },
volume: { type: Number },
isDividendAdjusted: { type: Boolean },
isSplitAdjusted: { type: Boolean }
}, { collection: 'equityHistories', versionKey: false });
Here's the Mongoose query for the first JSON result above:
mongo.EquityHistoryModel.aggregate([
{
"$match":{
"_id.equityIdentifier.exchange":passed_in,
"_id.equityIdentifier.symbol":passed_in,
"_id.instant":passed_in
}
},
{
"$project":{
"_id":0,
"openValue":"$open",
"timestamp":"$_id.instant"
}
}
],
You can also overwrite the toJSON method:
// Never return '__v' field and return the 'price' as String in the JSON representation
// Note that this doesn't effect `toObject`
EquityHistoryModel.set('toJSON', {
getters: true,
transform: (doc, ret) => {
if (ret.price) {
ret.price = ret.price.toString();
}
delete ret.__v;
return ret;
},
});
Contrary to what I expected, it seems the values are automatically extracted. Stringifying the result automatically wraps the value in the NumberDecimal. See the code with the output manually placed below:
console.log(docs[0].openValue);
119.800
console.log(JSON.stringify(docs[0].openValue]);
{"$numberDecimal":"119.800"}
Also, I struggled with sending query results, due to res.json or res.send using stringify. Instead I wrote a replace function and set the property in Node.
I have a collection like this (very simplified)...
var parentSchema = new mongoose.Schema({
firstName: String,
mobile: String
});
var familySchema = new mongoose.Schema({
groupId: { type: mongoose.Schema.Types.ObjectId, index: true },
parents: [parentSchema]
});
For a given group, I'd like to find all of the parents of families in that group who have a mobile value set (exists), and unset those mobile values.
I've been able to piece this much together by looking at other examples...
Family.update(
{ groupId: someGroupId, "parents.mobile": {"$exists":"true"} },
{ $unset : { "parents.$.mobile" : 1 } }, false, true
).then(function() {
// do other stuff
});
Running generates the error:
Trace: [Error: Invalid callback() argument.]
I've tried several variations, but this one seems the most correct to me.
The .update() signature for mongoose models is:
Model.update(<{query}>,<{update}>,[<{options}>],[callback])
So when using promises, it's just the first two with the optional "third" options. The "fourth" would be a callback function, and hence the error:
Family.update(
{ "groupId": someGroupId, "parents.mobile": {"$exists": true } },
{ "$unset": { "parents.$.mobile" : "" } },
{ "multi": true }
).then(function() {
Too many people read the "shell" signature, even though the usage of:
.update(<{query}>,<{update}>,<upsert>,<multi>)
Has been deprecated in favour of the standard "options" arrangement for some time.
Always refer to the method that actually applies to your language API.
I am just learning how to build websites using MEANJS, and I am structuring my data but unsure on the best practice, I am very new to the NoSql concept.
I need to store:
questions
answers
likes
saved_questions
In my app I enable the user to save questions to be viewed later, as well as they can access any answer they posted. And I provide some stats for each question (i.e. number of likes, number of answers, etc)
Should I create one document for "question" and everything inside of it:
{_id: <ObjectId>,
user_id: <ObjectId>,
question: 'how can we....',
answers: [{user_id: <ObjectId>, answer: ''}],
likes: [{user_id: <ObjectId>}],
saves: [{user_id: <ObjectId>}]
}
Or should I make multiple documents for each? Or should I use both methods?
I would have at least two database models, maybe one for the User and the other for the Question. One of the great things about the MEAN.JS boiler plate is that it already comes with a User module complete with sign-up, login/logout functionality. So you have that out of the way as soon as you deploy your new project.
With that already out of the way, I would use the Yo Generator to create a new CRUD module called Question. You can add the files manually, but Yo helps you do it quickly and accurately by automatically placing the files in the correct place, complete with sample code to help you set it up. To learn how to use the Yo Generator I would look at the Yo Generator Section of the MEAN.JS docs.
From your app's root directory, run yo meanjs:crud-module Question. This will create all of the necessary files you need for the database model, as well as a new module on the front & back ends with samples of how to create/read/update/delete the questions. Now, if you log in, you will see the new module in your menu bar.
Then open app/controllers/models/question.server.model.js. This is the file that you can define your new database model. Depending on how complex/relational you want the data to be, you'd want your Mongoose model to look something like this:
var QuestionSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
question: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
answers: {
type: Array,
default: []
},
likes: {
type: Array,
default: []
},
saves: {
type: Array,
default: []
}
});
Obviously this is very simplified. You may want to create separate mongoose models for the likes, saves, and reports so you can store more data about each (ie: user_id, date, reason for reporting/saving/liking, etc.) To read more about how to make the perfect mongoose model for your needs, I would definitely check out the docs about Mongoose Schemas at mongoosejs.com.
I hope that helps!
Continued...
To get a list of a given user's actions, I would go ahead and make a new Mongoose Schema for each type of action (comments, likes, saves), and store the details of user's actions there. For instance, in Answers schema you could store the actual comment, who said it, when they said it, what question it was for etc. Then simply query the action tables for a given user ID to retrieve your list of actions.
So..
var QuestionSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
question: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
var AnswerSchema = new Schema({
created: {
type: Date,
default: Date.now
},
question: {
type: Schema.ObjectId,
ref: 'Question'
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
answer: {
type: String,
default: '',
trim: true
}
});
I'm storing a price value in my Mongoose schema according to the answer from how should i store a price in mongoose?
I have the following code in my schema definition:
price: {
value: {
type: Number,
get: getPrice,
set: setPrice,
min: 0
},
currency: {
type: String,
default: 'PLN',
trim: true,
enum: ['PLN', 'EUR']
}
},
and my get function:
function getPrice(num){
return (num/100).toFixed(2);
}
However, whenever this getter function is called I can see that the num parameter in undefined.
Do you know what might be the reason for that? And how could I fix this?
Add a default of zero for value. Also, mongoose is notoriously bad about subdocuments that are not inside an array, which may be causing this problem.
value: {
type: Number,
get: getPrice,
set: setPrice,
min: 0,
default: 0
},
If getter/setters give you problems with mongoose models, use the native static methods in mongoose schemas:
mySchema.static('getPrice', function(){
//'this' in the context means a document that shares the schema
return (this.price.value/100).toString(2);
});
You can invoke the method in any document that have said schema:
var myPrice = oneMongooseDocument.getPrice();
Is a very clean approach.