I have a simple query that fetches data from MongoDB. The query returns an array of objects in which the seller ID matches. I want to change a particular field in all of the returned objects. Is there a more efficient way than to use map?
I have added the query here:
Order.find({ sellerId: sId })
.populate("address")
.exec((err, result) => {
if (err) {
return res.status(403).json({
error: err,
});
}
return res.status(200).send(result);
});
And this is the API response:
[
{
"orderDate": "2022-04-21T13:16:22.198Z",
"sellerId": "6212072976836b7c70d3dcb1",
"__v": 0
}
]
I want to change order date for each object in the object of arrays returned.
Related
I'm building REST APIs in node.js using express.js library.
For the embedded data stored in mongodb as json object, I'm trying to get specific data by filtering, thereby using the aggregate match to achieve so.
For the users collection, I've the data as below
[
{
unique_key:"1",
user_form:
{
user_details:
{
first_name:"Tely",
last_name:"Zed"
}
}
},
{
unique_key:"2",
user_form:
{
user_details:
{
first_name:"Rock",
last_name:"Monty"
}
}
}
]
I want to get data of user by searching name. So I'm using aggregate method and then using match operator to achieve it.
User is the name of the model.
For filtering I'm using below aggregate method on User model.
User.aggregate([
{
$match: {
user_form:
{
user_details:
{
first_name: req.body.user_form.user_details.first_name
}
}
}
}
])
.exec(function(err,filteredUsers){
if(filteredUsers) {
console.log(filteredUsers);
res.json({
"msg": "Successfully gets the filtered users",
"data": filteredUsers,
"success": true
});
} if(err){
res.json({
"msg":"Error occured while filtering users",
"error": err ,
"success":false
});
}
})
//Now when I'm posting request from postman with searching with first_name as Rock in postman //body as shown below.
{
user_form:
{
user_details:
{
first_name:"Rock"
}
}
}
//So upon hitting send, I'm getting below response in postman, so I'm not able to get filtered //data instead getting an empty array.
{
"msg": "Successfully gets the filtered users",
"data": [],
"success": true
}
So please tell what should I do to filter data .
Used dot notation to query for subdocument.
db.users.aggregate([
{$match:{"user_form.user_details.first_name":"Rock"}}]).pretty()
Output:
{
"_id" : ObjectId("63c01a42232f174edd983fbf"),
"unique_key" : "2",
"user_form" : {
"user_details" : {
"first_name" : "Rock",
"last_name" : "Monty"
}
}
}
The mistake I did was I kept a space in "first_name" like "first_name " while inserting the document, so that's why I wasn't able to get filtered data by dot notation method also, so later I did found by same query.
Im very new with nodejs. I want to check in mongodb if the value is exist or not, if exist, update linkview, if does not exist i want to push an object into array. Can anyone help me on how to write a statement to check the value is exist or not in db? Please help
So this is Admin schema
{
"_id": "67324b2cc6817758118e9557d8",
"name": "James",
"__v": 0,
"affiliatelink": [
{
"storeId": 60014d6e7286763490c3543,
"storeName": white choc,
"linkview": 1
}
]
}`
and this is my current code.
Admin.findById(adminId).then(admin =>{
if(admin){
//if affiliatelink.storeId = storeId(exist)
Admin.update({ _id: adminId, "affiliatelink.storeId": storeId}, {$inc: {"affiliatelink.$.linkview": 1}},
(err, result) => {
if (err) {
console.log("error "+err)
}
else {
//push an object into array
}
});
i try to do this way just to check the if else statement is working or not. but its not working.
const res = await Admin.find({"affiliatelink.storeId":storeId; //use async in function definition
console.log(res);
if (check in res) {
console.log("item is existed")}
else {
console.log("item is not existed")
}
In your third code snippet, you are doing a find operation which will return an empty array of [] which will be considered as true, hence that is the reason why the control is not going inside the else condition.
Use findOne instead of find (if the storeId is unique) else just check the length of the response of the query if it is greater than or equal to 0.
I am new to DynamoDb. I am trying to access an object inside the array:
Created a new item in a table-
survey.create({
survey_name: 'Cycle',
description: 'Describe me',
test:[{
title:'hello1'
},{
title:'hello2'
}]
}, function (err, survey) {
if(err){
console.log(err)
}else{
console.log('created', survey.get('survey_name'));
}
});
I am not to able to fetch "test[n].title", getting 0 results.
survey.query('Cycle')
.filter('test.title').equals('hello2') //Tried it with test[0].title also
.exec((err,data)=>{
if(err){
console.log(err);
}
else{
console.log(data);
}
});
Also, I want to retrieve a part(json) of the item of a table ie. 'test' if its possible
Querying DynamoDB using filters requires the key you are filtering on to be the top level key. You cannot filter using a nested object key.
I have a collection of fixtures that 'belong' to a competitor and look something like this:
{
"_id": {
"$oid": "59dbdf6dbe628df3a80419bc"
},
"timeOfEntrance": "1507581805813",
"timeOfFinish": null,
"competitor": {
"$oid": "59db5a3f3d6119e69911a61a"
},
"__v": 0
}
My goal is to update only the document's timeOfFinish by sending a PUT request with competitor's ID as a param in the url and timestamp in the body. However I'm struggling to compose the update query.
The following is what I have currently, it never finds the right match and to my surprise it's always updating the wrong document.
fixtureController.put = (req, res) => {
const competitorId = req.params.id;
const timeOfFinish = req.body.timeOfFinish;
Fixture.findOne({'competitor.$oid': competitorId}, (err, fixture) => {
fixture.set({ timeOfFinish });
fixture.save()
.then(updatedFixture => {
return res.status(200).json({
success: true,
fixture: updatedFixture
})
})
.catch(err => {
return res.status(500).json({
message: err
});
});
});
};
Bit of a beginner in the MongoDB field, will appreciate your comments and solutions.
Turns out there was no need to specify the exact field in the match parameter. Mongoose matches by the id field automatically.
Fixture.findOne({'competitor': competitorId}, (err, fixture) => {
...
});
I've got a collection of spellbooks in a mongodb. One of my API calls in express through mongoose is a PUT where the user provides the ID of the document and then a body that contains an array of spells. I want to update the array of spells in the spellbook document with the array brought in from the client.
Here's what the document looks like:
{
"_id": {
"$oid": "56f999342c2bdee43869c33b"
},
"name": "malagar22",
"username": "zak",
"spells": [
"56bd4da932c3b8e88e3c113a",
"56bd4da932c3b8e88e3c113b"
],
"__v": 0
}
Here's what my API call looks like:
app.put('/api/spellbook/:id', function (req, res) {
Spellbook.findById(req.params.id, function(err,spellbook) {
if (err) {
res.json({info:'error during find spellbook',error:err});
};
if (spellbook) {
_.merge(spellbook, req.body);
spellbook.save(function(err) {
if (err) {
res.json({info:'error updating spellbook',error:err});
};
res.json({info:'spellbook updated successfully'});
});
} else {
res.json({info:'spell not found'});
}
})
});
As you can see, I'm finding the spellbook that matches the ID. Then I'm doing a lodash merge with the request body, which I imagine would match the spells array in the document with the spells array in the body, which I'll post below. Then we update.
Here's my request:
{
"spells":[
"56bd4daa32c3b8e88e3c1148"
]
}
I'm getting the success callback, but when I check the database, the document isn't being updated. Sorry if this is really simple. I'm an MS SQL guy and this is my first time using Express and Mongo.