Mongoose `findById` not returning expected document - javascript

When I find a document using the following line:
const user = await User.findById(req.user.id).populate('input')
And then I console.log user, I can see the document that fulfills the query.
However, when I add .updateOne({ formResponded: '1' }); to the previous line like so:
const user = await User.findById(req.user.id).populate('input').updateOne({ formResponded: '1'});
and I console.log user I do not get any record but instead an object that looks like this:
{ n: 1,
nModified: 1,
opTime: {
ts: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1635212112 },
t: 41
},
electionId: 7fffffff0000000000000029,
ok: 1,
'$clusterTime': {
clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1635212112 },
signature: { hash: [Binary], keyId: [Long] }
},
operationTime: Timestamp { _bsontype: 'Timestamp', low_: 2, high_: 1635212112 }
}
Why does this happen?

Fixed:
const user = await User.findByIdAndUpdate({ _id: req.user.id }, { formResponded: '1' }).populate('input')

Related

How to find an ID inside a document property (array) and return the populated information of that object

I have the following document in MongoDB. How can I find a specific ID inside the likes array and return the populated information of that object?
This is the document:
{ _id: ObjectId("60a90f0e1f4af802e8b893e6"),
status: 'Available',
likes:
[ ObjectId("60a8e0b9baa1572b847931ed"),
ObjectId("60aa342cb6b39e3024453465") ],
name: 'coba',
age: '1 Year',
__v: 0 }
This is the function I have tried but it's returning a 404 error, though as you can see the id actually exists in the likes array.
const [foundUser] = await PetsModel.find(
{
likes: { $in: ["60a8e0b9baa1572b847931ed"] }
},
{ likes: 1 }
).populate({
path: 'likes',
select: {
__v: 0,
createdAt: 0,
updatedAt: 0,
password: 0
}
});
res.status(201).json({
success: true,
data: foundUser.likes
});
There you are telling MongoDB to search a string, not an id. So you have to convert the string into an id so MongoDB can search it. The code should look like this:
const mongoose = require('mongoose');
const [foundUser] = await PetsModel.find(
{
likes: { $in: [ mongoose.Types.ObjectId("60a8e0b9baa1572b847931ed") ] }
},
{ likes: 1 }
).populate({
path: 'likes',
select: {
__v: 0,
createdAt: 0,
updatedAt: 0,
password: 0
}
});
res.status(201).json({
success: true,
data: foundUser.likes
});

Unable to update record in MongoDB using findOneAndUpdate

I am using Mongoose to update an Announcement record, with the following definition:
const { DateTime } = require('luxon');
const Schema = new mongoose.Schema({
title: String,
description: String,
date: {
type: Date,
set: (dt) => dt.toJSDate(),
get: (d) => DateTime.fromJSDate(d),
},
club: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Club',
},
});
I am performing the update operation in this function
exports.update = async (id, params) => {
console.log(params)
await Announcement.findOneAndUpdate({ _id: id }, params, {
upsert: true,
useFindAndModify: false,
});
return "exports.get(id)";
};
However, I get an error when running Announcement.findOneAndUpdate:
$set' is empty. You must specify a field like so: {$set: {<field>: ...}}
This is what the params look like:
{
title: 'Name!',
description: 'Description!',
date: DateTime {
ts: 1601524800000,
_zone: LocalZone {},
loc: Locale {
locale: 'en-US',
numberingSystem: null,
outputCalendar: null,
intl: 'en-US',
weekdaysCache: [Object],
monthsCache: [Object],
meridiemCache: null,
eraCache: {},
specifiedLocale: null,
fastNumbersCached: null
},
invalid: null,
weekData: null,
c: {
year: 2020,
month: 10,
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
},
o: -240,
isLuxonDateTime: true
},
club: '99cb91bdc3464f14678934ca'
}
I know that all the ObjectId's are valid because I have tested them from Mongo shell. However, I can't figure out why I am not able to run findOneAndUpdate on an Announcement record.

How can I loop a sequelize response

If I make a request to a Postgres database with Sequelize, I get the next result:
[
Tags {
dataValues: { idtag: 18 },
_previousDataValues: { idtag: 18 },
_changed: {},
_modelOptions: {
...
},
_options: {
...
},
isNewRecord: false
},
Tags {
dataValues: { idtag: 19 },
_previousDataValues: { idtag: 19 },
_changed: {},
_modelOptions: {
...
},
_options: {
...
},
isNewRecord: false
},
Tags {
dataValues: { idtag: 20 },
_previousDataValues: { idtag: 20 },
_changed: {},
_modelOptions: {
...
},
_options: {
...
},
isNewRecord: false
}
]
I can't find the way to loop this to can get the 'idtag' values.
I tried to parse this to JSON with JSON.stringify() but it gives me a string. Also, I tried to loop this like it was an array but it didn't works too.
Let's assume that your output is stored to an array. Now using following piece of code you can collect idTag values.
const idTagVals = [];
array.forEach(element => {
idTagVals.push(element.dataValues.idtag);
});
console.log(idTagVals); //[ 18, 19, 20 ]
According to sequelize docs
TagsModel.findAll({where: {} ,plain:true});
Will return Array of plain objects.
And finilly I have the answer. First I converted the result with JSON.stringify() and then with JSON.parse().
let tags = await models.Tags.findAll({ attributes: ['idtag'], where: { iduser: iduser } });
let string = JSON.stringify(tags);
tags = JSON.parse(string);
And finally, to loop:
tags.forEach(async (tag) => {
...
});

Why eth.contract.Transfer returns only select transactions?

I am trying to get all transfer events of an ERC-20 token. But using web3.contract.event.eventName returns only select events of some 12 hours ago.
Where I am going wrong?
Current Block is : 8514062; But latest transaction I got is of block 8510432
tokenContract.events.Transfer({
fromBlock: 8510000,
toBlock: 'latest'
}, function (error, events) {
}).on('data', function (event) {
console.log(event);
})
Address I am following: 0xB8c77482e45F1F44dE1745F52C74426C631bDD52
Last transaction I am getting:
{ address: '0xB8c77482e45F1F44dE1745F52C74426C631bDD52',
blockHash: '0x8c822492376ee6bab76b8534f067631c2b149568c030953378cbc45733609528',
blockNumber: 8510432,
logIndex: 54,
removed: false,
transactionHash: '0x7a416f681333e5147268913382ad7995b372151a7716544e9a97fef4e23d3974',
transactionIndex: 24,
transactionLogIndex: '0x1',
type: 'mined',
id: 'log_51f5ea6e',
returnValues:
Result {
'0': '0xEee90e509a639E95E3BB502B17A0eEd6E014BFc0',
'1': '0x751b934E7496E437503D74D0679A45E49C0B7071',
'2': '2960491170000000000',
from: '0xEee90e509a639E95E3BB502B17A0eEd6E014BFc0',
to: '0x751b934E7496E437503D74D0679A45E49C0B7071',
value: '2960491170000000000' },
event: 'Transfer',
signature: '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
raw:
{ data: '0x0000000000000000000000000000000000000000000000002915c708a487d400',
topics: [Array] } }

Issue finding mongoose ObjectID in array of strings representing ObjectIDs

I need to find the index of the mongoose objectID in an array like this:
[ { _id: 58676b0a27b3782b92066ab6, score: 0 },
{ _id: 58676aca27b3782b92066ab4, score: 3 },
{ _id: 58676aef27b3782b92066ab5, score: 0 }]
The model I am using to compare is a mongoose schema with the following data:
{_id: 5868d41d27b3782b92066ac5,
updatedAt: 2017-01-01T21:38:30.070Z,
createdAt: 2017-01-01T10:04:13.413Z,
recurrence: 'once only',
end: 2017-01-02T00:00:00.000Z,
title: 'Go to bed without fuss / coming down',
_user: 58676aca27b3782b92066ab4,
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false }
I am trying to find the index of the model._user in the array above using the following:
var isIndex = individualScores.map(function(is) {return is._id; }).indexOf(taskList[i]._user);
Where individualScores is the original array and taskList[i] is the task model. However, this always returns -1. It never finds the correct _id in the array.
I guess your problem is related to how _id are returned by your query
If you get _id as String, your code should work, check the snippet below
But if instead, you get ObjectsIds, you have to cast them to String first
var individualScores = [
{ _id: "58676b0a27b3782b92066ab6", score: 0 },
{ _id: "58676aca27b3782b92066ab4", score: 3 },
{ _id: "58676aef27b3782b92066ab5", score: 0 }
]
var task = {
_id: "5868d41d27b3782b92066ac5",
updatedAt: new Date("2017-01-01T21:38:30.070Z"),
createdAt: new Date("2017-01-01T10:04:13.413Z"),
recurrence: 'once only',
end: new Date("2017-01-02T00:00:00.000Z"),
title: 'Go to bed without fuss / coming down',
_user: "58676aca27b3782b92066ab4",
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false
}
var isIndex = individualScores.map(
function(is) {
return is._id;
})
.indexOf(task._user);
console.log(isIndex)
I think your process should working well that you are using just only need to convert 'objectID' to String to compare. Convert using .toString() for both of _id and _user.
like bellow:
var isIndex = individualScores.map(function(is) {
return is._id.toString();
}).indexOf(taskList[i]._user.toString());

Categories