Node js --> Mongo Db Deleting a record using _id - node.js

I am trying this query and it doesn't give an output.
node
`app.delete("/:id",async (req,res)=> {
console.log(req.params.id)
const data = await dbConnect();
const result = await data.deleteOne({_id: new mongoDb.ObjectId(req.params.id)})
res.send(result)
})`
the data i am trying to delete is
database
`{
"_id": {
"$oid": "63ee1bd3a33473e6cee16b3d"
},
"name": "Vikram",
"age": "23 yrs",
"alive": true,
"mob": 54846516
}`
Now I am not able to handle this "$oid" help.
The data should get deleted using _id from the record.

Related

Mongodb update all the documents with unique id

I have collection with name products with almost 100k documents. I want to introduce a new key called secondaryKey with unique value uuid in all the documents.
I do this using nodejs.
Problem I am facing:-
When I try the below query,
db.collection('products').updateMany({},{"$set":{secondaryKey: uuid()}});
Here it updates all the documents with same uuid value,
I try with loop to update document one by one,but here issues is I don't have filter value in updateOne because I want to update all the documents.
Can anyone please help me here.
Thanks :)
If you are using MongoDB version >= 4.4 You can try this:
db.products.updateMany(
{},
[
{
$set: {
secondaryKey: {
$function: {
body: function() {
return UUID().toString().split('"')[1];
},
args: [],
lang: "js"
}
}
}
}
]
);
Output
[
{
"_id": ObjectId("..."),
"secondaryKey": "f41b15b7-a0c5-43ed-9d15-69dbafc0ed29"
},
{
"_id": ObjectId("..."),
"secondaryKey": "50ae7248-a92e-4b10-be7d-126b8083ff64"
},
{
"_id": ObjectId("..."),
"secondaryKey": "fa778a1a-371b-422a-b73f-8bcff865ad8e"
}
]
Since it's not the same value you want to put in each document you have to use the loop.
In your loop, you have to update the current document of the iteration. So you have to filter with the _id in the updateOne
The above reply didn't work for me. Plus, it compromises security when you enable javascript on your database (see here $function and javascript enabling on database). The best way is to not overload your server, do your work on local as below:
const { nanoid, customAlphabet } = require('nanoid')
async function asdf() {
const movies = await client.db("localhost").collection("productpost");
var result2 = []
let result = await movies.find({}).toArray()
result.forEach(element => {
const nanoid = customAlphabet('1234567890', 10)
console.log(element.price)
element.price = 4
element.id = nanoid()
result2.push(element)
});
console.log("out reult2", result2)
await movies.deleteMany({})
await movies.insertMany(result2)
})
It will delete any objects on your collections and update with the new ones. Using nanoid as uniqueids.
This is the database object array after adding unique id:
{ "_id": { "$oid": "334a98519a20b05c20574dd1" }, "attach": "[\"http://localhost:8000/be/images/2022/4/bitfinicon.png\"]", "title": "jkn jnjn", "description": "jnjn", "price": 4, "color": "After viewing I am 48.73025772956596% more satisfied with life.", "trademark": "", "category": "[]", "productstate": "Published", "createdat": { "$date": "2022-04-03T17:40:54.743Z" }, "language": "en"}
P.S: Please backup your collection before doing this or filter the array on your needs for not going through all collection.

Document is inserted twice into MongoDB when using Mongoose create method

I am having below schema in my API which gets details of username and the products he added to the cart.
const mongoose = require('mongoose');
mongoose.connect('mongodb connection').then(()=>{
console.log('DB connection is successfull');});
const AutoIncrement = require('mongoose-sequence')(mongoose);
const cartSchema = new mongoose.Schema({
cartId : {
type : Number
},
username : {
type : String
},
productsInCart : [{
productId : {type : Number,required : true},
productName : {type:String},
quantity : {type:Number}
}],
statusOfCart : {
type : String,
default : 'Open'
}},{ timestamps: true });
cartSchema.plugin(AutoIncrement,{id : 'cart_seq',inc_field : 'cartId'});
let cartModel = mongoose.model('carts',cartSchema);
module.exports = cartModel;
As you can see in the above code I am also using the mongoose-sequence to make cartId as a auto-incremented field.
Now, I have a POST request which gets the below JSON in request body and adds it to the cart collection in the MongoDB using the create method.
{
"username":"admin",
"productsInCart":
[
{
"productId":1,
"productName":"Watch",
"quantity":4
},
{
"productId":2,
"productName":"Phone",
"quantity":5
}
]
}
The code inside the Route Handler for the POST request in Express API would look something like this
let ctMod = new cartModel();
ctMod.username = req.body.username;
ctMod.productsInCart = req.body.productsInCart;
let insCartData = await cartModel.create(ctMod,{new:true});
if(insCartData.length > 0)
{
return res.status(200).json({
message : `New items got inserted into the cart with the ID : ${insCartData.cartId}`,
data : insCartData
});
}
The above code inserts two entries into the collection like below instead of one
{
"statusOfCart": "Open",
"productsInCart": [],
"createdAt": "2021-01-04T15:25:35.188Z",
"updatedAt": "2021-01-04T15:25:35.188Z",
"cartId": 13,
"__v": 0
},
{
"statusOfCart": "Open",
"productsInCart": [
{
"_id": "5ff332a891aa170b60a21ea9",
"productId": 1,
"productName": "Watch",
"quantity": 4
},
{
"_id": "5ff332a891aa170b60a21eaa",
"productId": 2,
"productName": "Phone",
"quantity": 5
}
],
"username": "admin",
"createdAt": "2021-01-04T15:25:35.210Z",
"updatedAt": "2021-01-04T15:25:35.210Z",
"cartId": 14,
"__v": 0
}
can you help me understand why there is duplicate entries in my db?
I'm not sure why you are using cartModel.create(ctMod,{new:true}); inorder to create a new entry to your collection.
You can simply do like this :
let ctMod = new cartModel();
ctMod.username = req.body.username;
ctMod.productsInCart = req.body.productsInCart;
try{
let insCartData = await cartModel.save();
return res.status(200).json({
error:false,
message : `New items got inserted into the cart with the ID : ${insCartData.cartId}`,
data : insCartData
});
}
catch(err){
console.error("error inserting data", err);
return res.status(500).json({error:true, message:"Something went wrong :("}).
}
UPDATE :
Reason for the duplicate entry is that you are passing the {new:true} flag in the create API. It's used to return the updated document in the findOneAndUpdate method. But in create/save, the mongoose return the data by default. Hence the flag is not needed.If you omit the flag, duplicate entries can be prevented.
Also, as you are using the create method to save the new entry, you need not create an instance of the cartModel. ie.,
let ctMod = new cartModel();
can be just
let ctMod = {}
Hope it helps!

How to update a value inside mongodb with nodeJS?

I'm trying to update a value inside mogoodb array but is the problem
database?
"TempChannels": [{
"user": "299481590445113345",
"channel": "794869948878159884",
"settings": []
}, {
"user": "583363766750806043",
"channel": "795004103998308352",
"settings": []
}],
The part of the code that should update the user:
Data.TempChannels[0].user = Target.id
Data.save().catch(er => console.log(er))
Also, no error appears when I run the code. and when i console the data it returns a user which has updated but it is not actually saved in mongodb!
code
Data.save().then(() => console.log(Data.TempChannels[0].user))
this is the whole data
{
"_id": {
"$oid": "5ff0cd1ee3d9fd2d40d82d23"
},
"TempChannels": [{
"user": "299481590445113345",
"channel": "795014692522295326",
"settings": []
}, {
"user": "583363766750806043",
"channel": "795015273060892753",
"settings": []
}],
"Guild": "704158258201624657",
"Stats": "true",
"ChannelID": "795014681664290826",
"ParentID": "795014680556994610",
"LogChannelID": "795014683601010709",
"TempControlChannelID": "795014682518749274",
"DefaultSettings": {
"limit": null,
"name": null,
"bitrate": null,
"copyperms": null
},
"__v": 2
}
I'm filtering the data by Guild
if you are using mongoose to connect MongoDB, the
Use markModified("updated field name")
Data.TempChannels[0].user = Target.id
Data.markModified('TempChannels');
Data.save().catch(er => console.log(er))
if you are using mongoose, there is a method that will allow to update the content of existing data
const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
If you are using Mongoose, you can update the record by doing something similar to this:
SchemaName.update({Guild: 'Guild Value Here'}, {$set: { "TempChannels[0].user" : "%newvalue%"}})
.then((data) => {
console.log(data)
})
.catch(err => {
console.log.error(err);
});
You should replace schemaName with the name of your schema if you are using mongoose, and in case you are not using it, I think it would be better for you to start using it.

updating multiple different array object elements in mongodb with nodejs

mongodb collection:
"_id": ObjectId("5e2ac528e9d99f3074f31de7"),
"publications": [
{
"_id": ObjectId("5e2ac528e9d99f3074f31de8"),
"name": "Times of India",
"productCode": "TCE1",
"tradeCopies": 40
},
{
"_id": ObjectId("5e2ac528e9d99f3074f31de9"),
"publicationName": "Economic Times",
"productCode": "ECE1",
"tradeCopies": 100
}
],
"orderCreatedBy": ObjectId("5e2977e1cc1208c65c00648b"),
"submittedTo": ObjectId("5e2555363405363bc4bf86c2"),
Nodejs Code
i would get multiple "productCode" like "TCE1","ECE1" etc,and i need to update tradeCopies of all the object array elements in one go according to their productCodes
Here is what i tried
exports.editOrder = async (req, res, next) => {
const { orderId, dealerId, productCode, tradeCopies } = req.body;
try{
const orders: await Order.updateOne(
{ _id: orderId,
submittedTo: dealerId,
"publications.productCode": productCode},
{$set:{"publications.$.tradeCopies":50}}
)
res.status(200).json({
orders,
message: "order submitted"
});
} catch (error) {
res.send(error);
}
};
CONCERNS
1-this query is updating only 1 array object element according to the matched productCode i want all the tradeCopies of all the array objects according to their productCodes to be updated in onego
2- the above query is working only in mongo Shell not in nodejs driver and whenever i remove double quotes in nodejs query vscode shows there might an error
You want to use arrayFilters.
const orders: await Order.updateOne(
{ _id: orderId,
submittedTo: dealerId,
"publications.productCode": productCode
},
{ $set: { "publications.$[element].tradeCopies":50 } },
{ arrayFilters: [ { "element.productCode": productCode } ] }
)
I'm not sure what you mean by removing the double quotes, but this snippet is nodejs driver compatible.

Get data from two different collections in mongodb in nodejs

i am new in mongodb database, i want to fetch data from two different collections ( like in mysql use of joins) then how can we do this in mongodb ? Here my collections data
First collection
{
"id": "5b67dbf20b9f9d2830ccaf40",
"title": "Some Text",
"author": "John Doe"
}
Second collection
{
"id": "5b67dbyd48btr9jexya8ehd8",
"pid": "5b67dbf20b9f9d2830ccaf40",
"salary": "50000"
}
Update your NewSchema as:
var NewSchema = mongoose.Schema({
pid: {
type: Mongoose.Schema.ObjectId,
ref: `Firstcollection`
}
});
You can solve it using populate from mongoose.
SecondCollection.find({})
.populate('pid')
.exec(function(err, data) {
console.log(data)
})
Hope it solves your query!!

Resources