why finding a record using objectId without await returns something else; - mongodb

**Any one know about this ?? **
This is my code , I want to know why it gives output like these
if(orderItem != null){
// orderItem = []
orderItem.forEach( async data => {
productData = await AdminDB.findById({_id: data.orderedItemId}) ; // here data.orderedItemId contains objectId as string
console.log(productData);
});
}
Without await
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
strictQuery: true,
strict: true,
pluralization: true
}, ** etc. etc ...and something like these**
with await
{
_id: new ObjectId("62af22d10cb99b48652d5d62"),
category: 'ghee',
quantity: '5',
amount: '12000',
productimg: 'https://images.pexels.com/photos/12447940/pexels-photo-12447940.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
__v: 0
} ** which returns record **

Related

Mongoose: $unshift with findOneAndUpdate is not working properly

I have this model:
const ProfileSchema = new Schema({
profileImageURLs: [
{
url: {
type: String,
},
current: {
type: Boolean,
},
date: {
type: Date,
default: Date.now,
},
},
],
});
And I have this function that updates the profileImageURLs field:
const updateProfileImageUrl = async (user_id) => {
const search_option = {
user: user_id,
};
const update_option = {
profileImageURLs: {
$unshift: {
url: `https://resources/profile_image`,
current: true,
},
},
};
const should_return_updated_profile = { new: true };
const updated_profile = await Profile.findOneAndUpdate(
search_option,
update_option,
should_return_updated_profile
);
console.log(
"🚀 ~ file: profileServices.js ~ line 1558 ~ updateProfileImageUrl ~ updated_profile",
updated_profile
);
};
The problem is the it is ignoring the values url and current in update_option and is only creating the _id and date fields:
profileImageURLs: [ { _id: 635ce632d633392b42c49094, date: 2022-10-29T08:37:06.012Z }]
And when I do a second update, instead of adding a new value to the beginning of the array, it creates a new array with the new values. So I have another array with a single object like that.
Any idea what's going on??
I used this instead and it works just fine:
const profile = await Profile.findOne(search_option);
profile.profileImageURLs.unshift({
url: profileImageURL,
current: true,
});
const updated_profile = await profile.save();

prisma findMany not returning id's of rows

Using prisma findMany to fetch rows from postgres database, but it's not returning the actual id of the row, just the other columns. I need the id so that I can pass that the frontend can use it for CRUD operations, is there a way to return those ID's?
const bookList = await prisma.books.findMany({
where: {
author_id: "123",
}
});
schema
model books {
id String #id #default(uuid())
name String #db.VarChar(50)
author_id String
}
Expected response
[{
"id": "some-uid",
"name": "some-book-name"
}]
^ it includes the id field, which I'm currently not getting
The default behaviour is to return all the fields in findMany but you can explicitly select fields that should be returned by select clause.
Here is an example:
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient();
// A `main` function so that you can use async/await
async function main() {
// ... you will write your Prisma Client queries here
const createBook = await prisma.books.create({
data: {
name: 'book1',
author_id: '1',
},
});
console.log('createBook:',createBook);
const books = await prisma.books.findMany({
where: {
author_id: '1',
},
select: {
name: true,
author_id: true,
id: true,
},
});
console.log('books:',books);
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});
Here's the response
createBook: {
id: '04a86b46-0348-4aa3-99d4-9a28365c020c',
name: 'book1',
author_id: '1'
}
books: [
{
name: 'book1',
author_id: '1',
id: '04a86b46-0348-4aa3-99d4-9a28365c020c'
}
]

Mongoose - Update/Find Specific Object in an Array Not Working As Expected

I am following the docs without luck and am at a standstill while trying to update an object in an object in an array using MongoDB and Mongoose.
Here is my document:
{
fields: [
{ id: 603d63086db2db00ab09f50f, data: [Object] },
{ id: 603d63086db2db00ab09f510, data: [Object] },
{ id: 603d63086db2db00ab09f511, data: [Object] },
{ id: 603d63086db2db00ab09f512, data: [Object] },
{ id: 603d63086db2db00ab09f513, data: [Object] },
{ id: 603d63086db2db00ab09f514, data: [Object] },
{ id: 603d63086db2db00ab09f515, data: [Object] }
],
layouts: [],
_id: 603d631a6db2db00ab09f517,
bandId: '603d63146db2db00ab09f516',
eventType: 'private',
ownerId: '6039354906410800c14934c1',
__v: 0
}
I am trying to updateOne of the fields.data in the fields array. fields.data is an object as well.
I call my Express/Node Backend to this route.
//Update
router.put("/:id", async (req, res) => {
try {
let updating = await QuoteGenerator.updateOne(
{ _id: req.params.id, "fields.id": req.body.id },
{
"$set": {
"fields.$.data": req.body.data,
},
}
);
let item = await QuoteGenerator.findOne({ _id: req.params.id });
res.json({ success: "Item Updated.", item });
} catch (err) {
console.log(err);
res.json({ error: "Something went wrong when updating this item." });
}
});
Where req.body is:
{ id: '603d63086db2db00ab09f50f', data: { type: 1, rate: '200.30' } }
**Just in case it's helpful, here is what one of the fields objects looks like in the document,
{"id":"603d63086db2db00ab09f50f","data":{"type":1,"rate":300}}
I have even tried changing my route to find this document - which I have confirmed exists - Truly at a loss why it won't find the document.
Here is how I changed the above route to find the document.
//Update
router.put("/:id", async (req, res) => {
try {
let updating = await QuoteGenerator.find(
{ _id: req.params.id, "fields.id": req.body.id },
);
console.log(updating) //returns []
let item = await QuoteGenerator.findOne({ _id: req.params.id });
res.json({ success: "Item Updated.", item });
} catch (err) {
console.log(err);
res.json({ error: "Something went wrong when updating this item." });
}
});
The Model
//Create Schema - QG
const QuoteGeneratorSchema = new Schema({
bandId: {
type: String,
required: true,
},
ownerId: {
type: String,
required: true,
},
fields: {
type: Array,
default: defaultFields,
required: true,
},
eventType: {
type: String,
required: false,
},
layouts: {
type: Array,
required: false,
},
});
let QuoteGenerator = mongoose.model("QuoteGenerator", QuoteGeneratorSchema);
module.exports = QuoteGenerator;
Any nudge in the right direction to replacing that data object with a new data object would be extremely helpful! Thanks!

fetching data from mongodb and electron js using ipc renderer

vue file
this.$electron.ipcRenderer.send('get-result')
this.$electron.ipcRenderer.on('got-it', (event, data) => {
if (data.status) {
this.allResult = data.result
}
else{
this.allResult = ''
}
})
renderer file
ipcMain.on('get-result', (event) => {
todolist.find({}, null, {sort: { creationDate: -1 }}, (err, result) => {
if (!err && result.length) {
event.sender.send('got-it', {
status: true,
result: result
});
} else {
event.sender.send('got-it', {
status: false
});
}
});
});
IN CMD results look like this which is OK
[ { _id: 5dd01fff35ad336558153f8c,
notes: 'hello 3',
creationDate: 2019-11-16T16:12:47.190Z,
__v: 0 },
{ _id: 5dd01efdca8cdf61daa07fcf,
notes: 'Hello Again',
creationDate: 2019-11-16T16:08:29.190Z,
__v: 0 },
{ _id: 5dd01d7a2a4b995f68d36f7c,
notes: 'Hello Mongo Atlas',
creationDate: 2019-11-16T16:02:02.998Z,
__v: 0 },
{ _id: 5dd01c72d43db25eb93c0267,
notes: 'hello mongo',
creationDate: 2019-11-16T15:57:38.799Z,
__v: 0 } ]
But after getting result from renderer browser console look like this
0:$__:(...)
$init:(...)
$locals:(...)
isNew:(...)
_doc:(...)
__ob__
:Observer {value: {…}, dep: Dep, vmCount: 0}
get $__:Æ’ reactiveGetter()
set $__:Æ’ reactiveSetter(newVal)
get $init:Æ’ reactiveGetter()
set $init:Æ’ reactiveSetter(newVal)
get $locals:Æ’ reactiveGetter()
set $locals:Æ’ reactiveSetter(newVal)
and final results are in under the _doc of every index like 0, 1, 2
why is that ? I think it supposed to return just simple array like CMD's printed result.
Is that anything left to fetching organize result or i need to do something else ?
Thank you
Best way ignore this type of format is, after getting result from DB encode in json and then of font-end decode json format which will generate desire result. Like this-
render.js
ipcMain.on('get-result', (event) => {
todolist.aggregate([
{
$sort:{
_id:-1
}
}
])
.exec((err, result) => {
if (!err && result.length) {
event.sender.send('got-it', {
status: true,
result: JSON.stringify(result)
});
} else {
event.sender.send('got-it', {
status: false
});
}
});
});
component.vue
this.$electron.ipcRenderer.send('get-result')
this.$electron.ipcRenderer.on('got-it', (event, data) => {
if (data.status) {
this.allResult = JSON.parse(data.result)
}
else{
this.allResult = ''
}
})

graphql query return object with null id

Graphql return Oject with null id.
with mongodb.
It looks strange to me.
If I delete new GraphQLNonNull() on MailType id,
It works with id: null, another fields working fine.
const MailType = new GraphQLObjectType({
name: 'Mail',
fields: () => ({
id: { type: new GraphQLNonNull(GraphQLID), },
...
})
const Query = {
mails: {
type: new GraphQLList(MailType),
args: {
senderId: { type: GraphQLID },
isOffline: { type: GraphQLBoolean },
},
async resolve(root, args, req, ctx) {
if (args.isOffline === false) {
let a = await model.aggregate([
{ $match: { isOffline: false } },
]);
let b = await model.find({ isOffline: false });
console.log(JSON.stringify(a) == JSON.Stringify(b)) /// return true
return a // error
return b // working
}
return model.find({senderId: args.senderId});
}
}
}
// with a
"errors": [
{
"message": "Cannot return null for non-nullable field Mail.id."
}]
I am in trouble for 2 hours but I do not get the answer.
Can anybody help me?
You probably have a mistake in your mongodb schema, not in graphQl.
make sure you did not define you id by id key, it should be _id.
for example if you are using mongoose it can be something like this:
const MailSchema = new Schema({
_id: {
type: String,
unique: true,
},
....
....
});