I am using MongoJS and would like to auto-create a new collection called "Comments" in my MongoDB via the code below...Not working and can't seem to figure out why. Thanks for any insight you can provide!
app.post("/post", function(req, res) {
db.comments.insert({
articleId: JSON.stringify(req.body._Id),
name: JSON.stringify(req.body.chatId),
message: JSON.stringify(req.body.message)
}),function(err, response) {
if(err) {
console.log(err);
} else {
console.log("This is working!");
}
}});
If you use the body-parse middleware:
app.post("/post", function(req, res) {
let { body } = req;
db.comments.insert({
articleId: body._Id,
name: body.chatId,
message: body.message
}),function(err, response) {
if(err) {
console.log(err);
} else {
console.log("This is working!");
}
}});
and if not , just use it like:
let parsed;
try {
parsed = JSON.parse(res.text)
} catch(err){req.send(err)}
// now you have:
parsed._Id ...
Related
I am trying to build a CRUD API that query a mongodb. I want to add another attribute (temperature) to the query result before sending it back to the client. Particularly, I would like to do something where the arrow pointed in the code below.
app.get('/items/:name', function (req, res) {
console.log("get items by name");
Item.find({ name: req.params.name }, function (err, result) {
if (err) {
res.status(400).send(err.message);
} else {
res.status(200).send(result); // <<<<====== Here
}
});
});
How can I achieve this function? Thank you.
i think this below way to help you:
app.get('/items/:name', function (req, res) {
console.log("get items by name");
Item.find({ name: req.params.name }, function (err, result) {
result = {
temperature: yourTemperatureValue,
...result
} // <<<<====== Here
if (err) {
res.status(400).send(err.message);
} else {
res.status(200).send(result);
}
});
});
I've got the next data in the MongoDB:
{
...
name: Alex,
createdAt: {"$date":"2021-03-09T20:01:57.488Z"},
...
}
And I try to implement the range date query like this:
MongoClient.connect(url, (err, db) => {
if (err) {
return reject(err);
}
const dbo = db.db('dbname');
dbo.collection('users').find({
createdAt: {
$gte: new Date(dateFrom).toISOString(),
$lt: new Date(dateTo).toISOString()
}
}).toArray(
(err, res) => {
if (err) { return reject(err); }
db.close();
return resolve(res);
});
});
And always have zero-result without errors..
How coud I do the right query?
I am trying to populate my array of an object id's how can i do ??
Function
$scope.assignEmployees = function () {
var chkArray = [];
var companyName = $scope.selectedComapny.companyName;
var Indata = {chkvalue:chkArray,company_name:companyName};
$("#employee_name:checked").each(function() {
chkArray.push($(this).val());
});
$http({
method : 'PUT',
url : '/api/projects',
data : Indata
})
.success(function (data){
console.log(data);
});}
Mongoose api
Population code:-
Project.findOne({client : company_name})
.populate('assignedTo')
.exec(function(err, project) {
if (err) return;
while(i<employee_id.length){
project.assignedTo.push(employee_id[i]);
project.save(function(err) {
if (err) return;
})
i++;
}
});
This code is work but it insert value 4 times any idea guys.
You can use this code to push all elements of Array to an Array in mongoose.
Project.update(
{ client: company_name },
{ "$pushAll": { "assignedTo": employee_id } },
function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
}
);
Im using the find() method to get all data from a mongoDB like this
exports.getPersona = function (req, res){
Persona.find( function(err, persona) {
if (err)
res.send(err)
res.json(persona); // return all personas in json
}
);
}
Im trying to do a query like this:
exports.getPersona = function (req, res){
Persona.find(
{
faceDetection: {
name: "Borja"
}, function(err, persona) {
if (err)
res.send(err)
res.json(persona);
}
);
}
But i dont find nothing. My mongoose model is:
var faceDetectionSchema = mongoose.Schema({
faceDetection: {
name: String,
surname: String,
}
});
What could be the problem? Thanks a lot.
Edit: the document its a JSON like:
{
"faceDetection": {
"name": "Borja",
"surname": "Good"
}
Looks like your parentheses and braces are out of order. Try this below.
exports.getPersona = function(req, res) {
Persona.find({
'faceDetection.name': "Borja"
}, function(err, persona) {
if (err)
res.send(err)
res.json(persona);
})
}
I developed a simple MEAN stack CRUD app. I deployed my site to azure websites. In my localhost the app work fine. But I want to connect with mongoLab database. How can I connect it?
This is the code for server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('posts', ['posts']);
var bobyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bobyParser.json());//
app.get('/posts', function (req, res) {
console.log("I got the server request!")
db.posts.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.post('/posts', function (req, res) {
console.log(req.body);
//Insert - This is the first part of the CRUD
db.posts.insert(req.body, function (err, doc) {
res.json(doc);
});
});
app.delete('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.posts.remove({ _id: mongojs.ObjectId(id) }, function (err, doc) {
res.json(doc);
});
});
app.get('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.posts.findOne({ _id: mongojs.ObjectId(id) }, function (err, doc) {
res.json(doc);
});
});
app.put('/posts/:id', function (req, res) {
var id = req.params.id;
console.log(req.body.name);
db.posts.findAndModify({
query: { _id: mongojs.ObjectId(id) },
update: { $set: { name: req.body.name, info: req.body.info, twitter: req.body.twitter }},
new: true
}, function (err, doc) {
res.json(doc);
});
});
app.listen(3000);
console.log("Server running from port 3000");
How can I make the connection? I have the connection info what azure provides.
Thanks a lot.
Can you look at the exact Exception error message?
Try something like the following:
try
{
smtp.Send(msg);
Response.Write("<script>alert('Mensaje enviado correctamente');</script>");
NullTextBox();
}
catch (Exception ex)
{
Response.Write(string.Format("<script>alert('There is an error on connection to DB on microsoft azure:{0}');</script>", ex.ToString()));
NullTextBox();
}