I want to get data from my database to work with variables.
Here is my database query:
db.progress.find({username:socket},function(err,res){
what do I get information on:
[ { _id: 61e180b54e0eea1454f8e5e6,
username: 'user',
exp: 0,
fraction: 'undf'} ]
if i send a request
db.progress.find({username:socket},{exp:1},function(err,res){
then in return I will get
[ { _id: 61e180b54e0eea1454f8e5e6, exp: 0 } ]
how do i extract only 0 from the received data. I would like to do something like this.
var findprogress = function(socket,cb){
db.progress.find({username:socket},function(err,res){
cb(res.exp,res.fraction)
})
}
findprogress(socket,function(cb){
console.log(cb.exp)//0
console.log(cb.fraction)//undf
})
but I don't know how to implement it correctly.
I recommend aggregate in this case so you can more easily manipulate your projected data. For example:
db.progress.aggregate([
{ $match: { username: socket } },
{ $project: { _id: 0, exp: 1 } }
])
This way you directly tell the query to not include the objectId, which is typically included by default.
find returns an array, so you will need to select the array element before accessing the field:
var findprogress = function(socket,cb){
db.progress.find({username:socket},function(err,res){
cb(res[0].exp,res[0].fraction)
})
}
Try to give 0 to _id:
db.progress.find({username:socket},{exp:1 , _id:0},function(err,res){
Related
I have got a data structure:
{
field: 1,
field: 3,
field: [
{ _id: xxx , subfield: 1 },
{ _id: xxx , subfield: 1 },
]
}
I need to update a certain element in the array.
So far I can only do that by pulling out old object and pushing in a new one, but it changes the file order.
My implementation:
const product = await ProductModel.findOne({ _id: productID });
const price = product.prices.find( (price: any) => price._id == id );
if(!price) {
throw {
type: 'ProductPriceError',
code: 404,
message: `Coundn't find price with provided ID: ${id}`,
success: false,
}
}
product.prices.pull({ _id: id })
product.prices.push(Object.assign(price, payload))
await product.save()
and I wonder if there is any atomic way to implement that. Because this approach doesn't seem to be secured.
Yes, you can update a particular object in the array if you can find it.
Have a look at the positional '$' operator here.
Your current implementation using mongoose will then be somewhat like this:
await ProductModel.updateOne(
{ _id: productID, 'prices._id': id },//Finding Product with the particular price
{ $set: { 'prices.$.subField': subFieldValue } },
);
Notice the '$' symbol in prices.$.subField. MongoDB is smart enough to only update the element at the index which was found by the query.
It receives data from the request body in the following format. Properly I have to insert it into the database but the format is not correct.
{
name: '123',
description: 'Dev',
"item_variants[0]['name']": '23434',
"item_variants[0]['quantity']": '12334',
"item_variants[0]['unit_price']": '123123',
}
And how to transform the following format? Everyone's answers help me some ideas. Thank you
{
name: '123',
description: 'Dev',
item_variants: [
{
name: '23434',
quantity: '23434',
unit_price: '23434',
}
]
}
In express, after getting this form body you have to store this response in any variable and reformate this response after formatting you can save it into the database.
try {
let inputs = req.body;
inputs = {
name: inputs.name,
description: inputs.description,
item_variants: [
{
name: item_variants[0].name,
quantity: item_variants[0].quantity,
unit_price: item_variants[0].unit_price,
},
],
};
// NOW you can save this formatted version into the database
const result = await Product.save(inputs);
} catch (e) {
console.log(e);
}
In item_variants name, quantity, unit_price you might change digging and getting value.
I have a MongoDB collection for storing chat objects with messages embedded as a nested array. The entire collection looks like this:
chats = [
{
_id: 0,
messages: [
{
_id: 0,
text: 'First message'
},
{
_id: 1,
text: 'Second message'
}
]
},
{
_id: 1,
messages: []
}
]
I would like to update a single message and return it to the user. I can update the message like this (in Node):
const chat = chats.findOneAndUpdate({
_id: ObjectId(chatID),
"messages._id": ObjectId(messageID)
}, {
$set: {
"messages.$.text": newText
}
});
The issue is that this query updates a message and returns a chat object, meaning that I have to look for an updated message in my code again. (i.e. chat.messages.find(message => message._id === messageID)).
Is there a way to get a message object from MongoDB directly? It would also be nice to do the update in the same query.
EDIT: I am using Node with mongodb.
Thank you!
Since MongoDB methods findOneAndUpdate, findAndModify do not allow to get the updated document from array field,
projection will return updated sub document of array using positional $ after array field name
returnNewDocument: true will return updated(new) document but this will return whole document object
The problem is, MongoDB cannot allowing to use a positional projection and return the new document together
For temporary solution
try using projection, this will return original document from array field using $ positional,
const chat = chats.findOneAndUpdate(
{
_id: ObjectId(chatID),
"messages._id": ObjectId(messageID)
},
{ $set: { "messages.$.text": newText } },
{
projection: { "messages.$": 1 }
}
);
Result:
{
"_id" : 0.0,
"messages" : [
{
"_id" : 0.0,
"text" : "Original Message"
}
]
}
To get an updated document, a new query could be made like this:
const message = chats.findOne({
_id: ObjectId(chatID),
"messages._id": ObjectId(messageID)
}, {
projection: {'messages.$': 1},
}).messages[0];
Result:
{
"_id": 0.0,
"text": "New message",
}
I have a structure like this:
{
...
_id: <projectId>
en-GB: [{
_id: <entryId>,
key: 'some key',
value: 'some value',
}]
}
And I've tried updating it with Mongoose (and raw mongodb too) like this:
const result = await Project
.update({
_id: projectId,
'en-GB._id': entryId,
}, {
$set: {
'en-GB.$.key': 'g000gle!!',
},
})
.exec();
I've checked that the IDs are correct. But it doesn't update anything:
{ n: 0, nModified: 0, ok: 1 }
What am I doing wrong? Thanks
As discussed in the comments on the question, the issue is directly related to passing in a string representation of an id in the query as opposed to using an ObjectId. In general, it's good practice to treat the use of ObjectIds as the rule and the use of string representations as special exceptions (e.g. in methods like findByIdAndUpdate) in order to avoid this issue.
const { ObjectId } = require('mongodb');
.update({
_id: ObjectId(projectId),
'en-GB._id': ObjectId(entryId),
})
Using Mongoose, How can I add more items to an object without replacing existing ones?
User.findOneAndUpdate(
{ userId: 0 },
{ userObjects: { newItem: value } }
);
The problem with above code is that it clears whatever was there before and replaces it with newItem when I wanted it just to add another item to userObjects(Like push function for javascript arrays).
Use dot notation to specify the field to update/add particular fields in an embedded document.
User.findOneAndUpdate(
{ userId: 0 },
{ "userObjects.newerItem": newervalue } }
);
or
User.findOneAndUpdate(
{ userId: 0 },
{ "$set":{"userObjects.newerItem": newervalue } }
);
or Use $mergeObjects aggregation operator to update the existing obj by passing new objects
User.findOneAndUpdate(
{"userId":0},
[{"$set":{
"userObjects":{
"$mergeObjects":[
"$userObjects",
{"newerItem":"newervalue","newestItem":"newestvalue"}
]
}
}}]
)
According to your question, i am guessing userObjects is an array.
You can try $push to insert items into the array.
User.findOneAndUpdate(
{ userId: 0 },
{ $push : {"userObjects": { newItem: value } }},
{safe :true , upsert : true},function(err,model)
{
...
});
For more info, read MongoDB $push reference.
Hope it helps you. If you had provided the schema, i could have helped better.
Just create new collection called UserObjects and do something like this.
UserObject.Insert({ userId: 0, newItem: value }, function(err,newObject){
});
Whenever you want to get these user objects from a user then you can do it using monogoose's query population to populate parent objects with related data in other collections. If not, then your best bet is to just make the userObjects an array.