how to update database with mongoose - javascript

I am trying to update MongoDB database with mongoose
Works but I can't get a call back with new data
Templates.updateOne((req.query, req.body))
does not work
Templates.updateOne(req.query, req.body, { new: true }, (err, data) => {
console.log("just call back", data);
})
the data that is coming from req.query
{title: "Hello World"}
the data that is coming from req.body
{_ref: "your ref}
I am hoping to be able to update with callback and new data to console.log

According to the doc, Document.prototype.updateOne() does not accept {new:true} (it is a native MongoDB command, I believe), but Model.findOneAndUpdate() does.

Related

Express / Mongo DB API Explanation

I am struggling to understand where and why I initialize my first newFruit in my .then() promise or where it is coming from in my controller JS file. I am working on an express / mongo DB API
Please explain .then line
const Recipe = require("../models/recipes.models");
module.exports.createRecipe = (req, res) => {
Recipe.create(req.body)
.then((newFruit) => res.json(newFruit))
.catch((errors) => res.status(400).json(errors));
};
What I think i understand currently is that my newFruit is equal to my req.body post information object and i am setting that as a successful json response for my API.
However I am confused on the flow of data and what my first newFruit does and why I need it. Does the req.body form Data just automatically get renamed to whatever I call it in my .then ?
Any Pseudo Code may help.
console log of newFruit from postman form
{
name: 'soup',
under30: true,
price: 400,
_id: new ObjectId("636d649d85c3df316383c409"),
createdAt: 2022-11-10T20:52:45.733Z,
updatedAt: 2022-11-10T20:52:45.733Z,
__v: 0
}

Duplicate object in MongoDB array using Mongoose

I have a Node.js app that is creating a 'unit' in the DB under a 'building' that is saving two 'units' inside the array included in 'building'. Both of these are identical in both data and created timestamp. Anyone have an idea why the below code would be causing this to happen? I am a bit confused at it. I don't see how it would be adding two objects to the array. The code is not being run twice, I checked that with console.log() and just looking at my API logs.
await Building.findOneAndUpdate(
{buildingID},
{"$push": {units: unitData}},
(err, doc) => {
if(err) {
logger.error(`POST unit/new save error for unit: ${unitID} - error message: `, err)
return res.json({success: false, err, message: 'Error saving new unit, please try again'})
}
logger.debug('POST unit/new save() doc: ', doc)
return res.json({success: true, message: `Successfully saved new unit with ID of: ${unitID}`, unitData})
}
)
I ended up figuring it out, when there is an await and a callback it will save the data twice. This is a documented issue on the MongoDB documentation.

POST http://localhost:3000/updateSurvey 400 (Bad Request)

I am trying to update a collection in mongoDB after the user finishes some tasks. However, whenever I attempt to save the information and update mongo, I'm getting the error POST http://localhost:3000/updateSurvey/634124db6f 400 (Bad Request). Any ideas why my code isn't functioning correctly?
Backend js script
app.post('/updateSurvey', async (req, res) => {
try {
await client.connect();
var db = client.db('Admin_Db');
var collection = db.collection('Survey');
await collection.findOneAndUpdate({"_id": ObjectId(req.body.id)}, {completion: req.body.completion});
res.send("updated");
} catch (error) {
console.log(error);
res.status(400).send(error);
}
});
Main.js (this is how I am fetching the data from mongo)
fetch("http://localhost:3000/updateSurvey", {
method:'POST',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({id: surveyID, completion: true})})
.then(response=>{response.text()})
.catch(function(err){console.log("Fetch Problem: " + err)});
You don't have a route http://localhost:3000/updateSurvey/634124db6f exposed on your server. Therefore the 404 error. Since you are using a post call, just pass the surveyID in your body when making the post call using fetchAPI instead of sending it as a query param.
And make sure http://localhost:3000/updateSurvey is the route to which your are sending your data, without the surveyId in the URL.
Edit
Edits made as per request received in comments.
collection.findOneAndUpdate({"_id": id)}, {completion: req.body.completion});
should be:
collection.findOneAndUpdate({"_id": new ObjectId(id))}, {completion: req.body.completion});
_id is of type ObjectId in MongoDB. You are passing id as string. This should most likely be the error from what I can gather by the code shared in your question. You can cast a string to ObjectId by using the ObjectId class provided by the Mongo Driver for node. Even mongoose provides this class.

Node.js SQL How to Run Query that Spans Over Two Databases

I am building an application that has a backend that uses SQL queries to get data from a SQL Server database. However, I need to write a query that truncates and repopulates a table in that database using data from a second database. Here is what my code looks like:
// establishes a connection to serverName and uses DB1 as the database. But how can you access two?
global.config = {
user: 'username',
password: 'password',
server: 'serverName',
database: 'DB1'
};
// run this query. It's already been tested in SQL server and works fine there
let query = "TRUNCATE TABLE [DB1].[dbo].[Shop]; INSERT INTO [DB1].[dbo].[Shop] (Shop, shopDescription, Address, City)" +
" SELECT Shop, Description, Address, City FROM [DB2].[dbo].[ShopTable]"
new sql.ConnectionPool(config).connect().then(pool => {
return pool.request().query(query) }).then(
result => {
console.log(result.recordset)
//result returns as "undefined"
res.setHeader('Access-Control-Allow-Origin', '*')
res.status(200);
sql.close();
}).catch(err => { //error is not thrown
res.status(500).send({ message: err})
sql.close();
});
I get an "undefined" result, and find that no update to the table was made. The issue here isn't exactly clear whether it can't reach the table in DB2, or if perhaps the command doesn't work with the Node.js mssql package?
It appears this was a front end to back end connection issue. I was able to get the query to work without any changes to the database information, so it appears I can access the second database without any issues.
component.ts
this.httpService.patch('update', {} ).subscribe()
index.js
app.patch('/api/update', controllers.manualQueries.update);

ExpressJS response to POST is undefined after accessing MongoDB?

I'm making a web application using the MEAN framework and MVC design pattern. I am trying to perform a POST request from the Angular front-end for finding a document in my server-side MongoDB (version 2.4.9). The console logs show that the query is successful, but when I try to send the response back to the client, the query result is undefined.
I understand that NodeJS is asynchronous and uses callbacks, but I am having trouble understanding what is wrong with my code. I tried using returns and callbacks but I can't get it working. I'm confused how to use the controller to access the model and have the controller ultimately send the response.
Here is my code to connect to the database (model):
module.exports = {
readDocument : function(callback, coll, owner) {
// Connect to database
MongoClient.connect("mongodb://localhost:27017/tradingpost", function(err, db) {
if (err) {
console.log("Cannot connect to db (db.js)");
callback(err);
}
else {
console.log("Connected to DB from db.js: ", db.databaseName);
//Read document by owner
// Get the documents collection
var collection = db.collection(coll);
// Find document
collection.find({owner: owner}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found:', result);
} else {
console.log('No document(s) found with defined "find" criteria!');
}
// Close connection
db.close();
return callback(result);
});
}
})
}}
And here is my controller that sends the response:
var model = require('../models/db');
exports.sendRecentPosts = function (req,res) {
// Connect to the DB
// Run query for recent posts
// Close the connection
// Send the data to the client
var result = model.readDocument(dbCallback, "gs", "Mana");
res.end( result );
};
Client's post request:
// Use post for secure queries
// Need recent posts for display
$http.post('/recent').
success(function(responseData) {
$scope.testValue = responseData;
}).
error(function(responseData) {
console.log('Recent posts POST error. Received: ', responseData);
});
Snippet for my express route:
var goodsServices = require('../controllers/gs-server-controller.js');
app.post('/recent', goodsServices.sendRecentPosts);
I have been struggling with this for a long time and searched the forum for solutions but could not find any. Thanks for any feedback.
I do not know why this question has not been answered yet. When I faced the same problem, I learnt that the response to all DB queries are returned after the DB transaction is complete. Try placing db.close() within the success callback response of the find() call.

Categories