Good morning everyone.
So I'm doing a class assignment wherein I'm connecting to an existing mongoDB database (via a node.js server), and I'm adding a bunch of data to it from a form on an HTML site. I've got the form information adding correctly, but there's two fields server side that aren't responding to new data. There is the primary key (_id) which instead of incrementing from the current last number, get's incremented by ObjectId('longnumericvale'), and CustomerID which get's populated by an undefined value. The last record existing in the database has both _id and CustomerId as the same number. How can I get node.js to look at this number and auto increment it when it's adding my form data as a new document in the mongodb DB. Code below:
app.post("/orderform", (req, res) => { //This takes post action from html and stores it
console.log("successfully posted")
var item = {
CustFirstName: req.body.CustFirstName,
CustLastName: req.body.CustLastName,
CustAddress: req.body.CustAddress,
CustCity: req.body.CustCity,
CustProv: req.body.CustProv,
CustPostal: req.body.CustPostal,
CustCountry: req.body.CustCountry,
CustHomePhone: req.body.CustHomePhone,
CustBusPhone: req.body.CustBusPhone,
CustEmail: req.body.CustEmail,
userid: req.body.userid,
passwd: req.body.passwd,
};
console.log("Customer information stored as:");//this is just a debug to the console to make sure it's grabbing the info
console.log(item);
//here we connect to the datbase, and insert every item above to its corresponding position in the "customers" collection of "travelexperts" database
mongo.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) throw err;
//select database
const db = client.db("travelexperts");
//grab a collection
const collection = db.collection("customers");
collection.insertOne(item, (err, res) => {
if (err) throw err;
console.log("Items inserted");
db.close;
});
});//endconnection
res.redirect('/thanks');
console.log("finished, redirected")
});
//render thank you page for after submitting order
app.get('/thanks', (req, res) =>{
res.render("thanks");
});
I've read the documentation for mongodb on autoincrementing, but it's a bit beyond me how to implement it in my specific example.
UPDATE
So maybe I didn't explain the problem really well. I'm trying to log into two separate collections now, and I have that working. with this code below:
app.post("/orderform", (req, res) => { //This takes post action from Order.html form and stores all form inputs with corresponding names in a variable called item
console.log("successfully posted")
var item = {
CustFirstName: req.body.CustFirstName,
CustLastName: req.body.CustLastName,
CustAddress: req.body.CustAddress,
CustCity: req.body.CustCity,
CustProv: req.body.CustProv,
CustPostal: req.body.CustPostal,
CustCountry: req.body.CustCountry,
CustHomePhone: req.body.CustHomePhone,
CustBusPhone: req.body.CustBusPhone,
CustEmail: req.body.CustEmail,
userid: req.body.userid,
passwd: req.body.passwd,
};
console.log("This should be an array of all entered customer info:");//this is just a debug to the console to make sure it's grabbing the info
console.log(item);
var book = {
BookingId: "",
BookingDate: new Date(),
BookingNo: "",
TravelerCount:"",
CustomerId: "",
TripTypeId:"",
PackageId: Number(req.query.packId),
};
console.log(book);
//here we connect to the datbase, and insert every item/booking above to its corresponding position in the "customers" collection of "travelexperts" database
mongo.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) throw err;
const db = client.db("travelexperts");
const collection = db.collection("customers");
const booking = db.collection("bookings");
collection.insertOne(item, (err, res) => {
if (err) throw err;
console.log("Items inserted");
});
booking.insertOne(book, (err, res) => {
if (err) throw err;
console.log("Items inserted");
});
db.close;
});//endconnection
res.redirect('/thanks');
console.log("finished, redirected")
});
So the issue is that for both collections and bookings, they have incomplete records. collections is 26 documents long, and the last _id is 144. So that's why I need to read that _id and increment it +1 for each new record. There's an _id field for each collection and then a customerId and BookinbId that should match it. Really appreciate all the help so far, but neither of these solutions seems to work. I tried both just before the collections.insertone line, and i tried console logging them and they just return [object Object] in the console instead of the _id value.
To insert a custom ID field for your documents, you should append the _id field with your item object.
The simplest wayc can be to create a global id_counter variable that you increment everytime you execute the /orderform API.
let idCounter = 1;
.
.
.
const itemDoc = {_id: idCounter++, ...item}
collection.insertOne(itemDoc, (err, res) => {
if (err) throw err;
console.log("Items inserted");
db.close;
});
.
.
.
You could also fetch the last inserted Item's id and simply increment it and it could save a lot of effort to keep the ids of the documents in sync incase the server restarts or something.
In that case, you could do something as below using collection.countDocuments() method:
let docLength = 0 // global variable
.
.
.
// inside your api endpoint controller...
collection.countDocuments({}, {}, (err, res)=> {
docLength = res;
})
const itemDoc = {_id: docLength++, ...item}
collection.insertOne(itemDoc, (err, res) => {
if (err) throw err;
console.log("Items inserted");
db.close;
});
I have many documents in a collection of mongoDB. I want to increase the start_dateTime field by the given duration in minutes and the given user_id.
But that collection contains multiple documents for the given user_id. So I want to increase all start_dateTime by the given duration and the given user_id.
I got the following error
MongoError: Cannot increment with non-numeric argument:
{start_datetime: new Date(1570701481175)}
function delayworkTime(req,res,next)
{
const usrId = req.body.user_id;
var delays_by = req.body.delays_by;
try
{
Works.updateMany( {user_id: usrId},
{$inc: {start_datetime : moment().add(delays_by, 'minutes')}}
)
.then(function (delays)
{
console.log(delaysss);})
.catch(function (err)
{
console.error(err);
});
}
catch (err)
{
return res.status(500).json(err);
}
}
dbo.collection('Gps').findOne({$skip: 50}, { captureDateTime :a5},function (err, result) {
if (result) {
dbo.collection("OBD").insertOne({ sensortype: 'OBD', captureDateTime: result.captureDateTime, vehiculeData: b5 }, function (err, result) {
if (err) throw err;
else
console.log('OBD matched with GPS');
})
}
});
Its not getting proper result. I want to skip the 50 records and then from remaining records I want matched records based on capturedatetime and push it in OBD collection.
I also tried for
dbo.collection('Gps').aggregate([
{$skip : 50},
{ $match : { captureDateTime : a5 } }
]).toArray( function (err, result) {
if (result) {
dbo.collection("OBD").insertOne({ sensortype: 'OBD', captureDateTime: result.captureDateTime, vehiculeData: b5 }, function (err, result) {
if (err) throw err;
else
console.log('OBD matched with GPS');
})
}
});
Might be this can solve your problem link: https://www.w3resource.com/mongodb/mongodb-skip-limit.php
dbo.collection('Gps').findOne().skip(50)
findOne() does not support skip(), since a document is retrieved rather than a cursor. You might use the following method instead :
db.getCollection('Gps').find({captureDateTime :"a5"}).skip(50).limit(1)
I want to limit the length of data returned by Model.find() in mongodb/mongoose
here is my code
Want to return 'Excerpt' from content.
Blog.find({},{
title: 1,
content: 1 // basically wants to return content not more than 200 character
}, function(err, data){
if (err) {
console.log(err);
}
res.render('blog/posts', {
title:'All posts',
posts: data
});
});
In other words how to return limited content from mongoDB
Update
Found solution:
Match with substring in mongodb aggregation
You just need to pass limit parameter in 3rd option
Blog.find({},{
title: 1,
content: 1 // basically wants to return content not more than 200 character
},{ limit:10 }, function(err, data){
if (err) {
// You should handle this err because res.render will send
// undefined if you don't.
console.log(err);
}
res.render('blog/posts', {
title:'All posts',
posts: data
});
});
I'm building pagination with mongoose/nodejs application and have the following code:
var Query = Model.find(
"location": {
"$geoWithin": {
"$box": [
[165.8694369, -52.61941849999999],
[175.831536, -29.2313419]
]
}
}
});
// Get count of documents
return Query.count(function (err, totalCount) {
if (err) throw err;
// Get paginated list
return Query.
find().
skip(skip).
limit(limit).
exec(function (err, results) {
if (err) throw err;
// return result
});
In the preceding code I get totalCount to build pagination on client-side and it works fine. But now I need to use aggregate instead find and trying the following:
// Construct pipeline
var pipeline = [{
"$geoNear": {
"near": [165.8694369, -52.61941849999999],
"distanceField": "distance"
}
}];
var Query = adModel.aggregate(pipeline);
// Get count of documents
return Query.count(function (err, totalCount) {
if (err) throw err;
But unfortunately I get the error count() method does not exists. How could I total count of documents with aggregation framework?
The problem is that Model.aggregate doesn't return a Query object that's why the count method does not exists.
Anyway since it returns a promise you can count your docs like this:
adModel.aggregate(pipeline).then(function (docs) {
console.log(docs.length);
});
and if you don't like promises you can still pass a callback:
adModel.aggregate(pipeline, function (err, docs) {
console.log(docs.length);
});