I copied documents from a local database to my production database and when I try to get the document by Id by running model.findOne({_id : id}) and mongoose returns nothing. I am copying the documents over with the same Id, but I also tried with a new Id. I can find the document in the database and confirm that the JSON is correct, the Id is correct, etc and it won't find it. The documents I did not copy and where generated via my app still query fine with the findOne command. So, I have no idea what's going on
any help is greatly appreciated, thanks
groups.crud
getGroupById(id: string) {
logger.debug(".getGroupById id: " + id);
return new Promise(function(resolve, reject) {
GroupsModel.findById(id)
.populate('createdBy')
.then(function (group) {
logger.debug(".getGroupById");
if(group.createdBy.privacySettings.useUserName) {
group.createdBy.firstName = '';
group.createdBy.lastName = '';
}
resolve(group);
})
.catch(function(error) {
reject(error);
});
});
}
groups.routes
getGroupById(req, res, next) {
logger.debug('.getGroupById: BEG');
let id = req.params.id;
return groupsCrud.getGroupById(id)
.then(function(group) {
if(group) {
logger.debug('.getGroupById: get by id success');
let response = {
data : group
}
logger.debug('.getGroupById: response: ' + response);
res.json(response);
}
else {
logger.debug('.getGroupById: get by id failed 1');
res.status(404).json({ status : 404, message : "Group not found."});
}
})
.catch(function(error) {
logger.debug('.getGroupById: get by id failed 2 err = ' + JSON.stringify(error, null, 2));
res.sendStatus(404);
});
}
Related
I'm trying to collection queries in the while loop. But I'm getting a "Query was already executed" error. How can I do that? I have a custom field and I need to make sure it is unique. I also need to use this function elsewhere.
async function createRandomID() {
let id = Math.random().toString(36).slice(2, 6).toUpperCase();
let unique = false;
while (!unique) {
await Deed.findOne({ deedId: id }, async (err, doc) => {
if (!doc) {
unique = true;
}
else {
id = Math.random().toString(36).slice(2, 6).toUpperCase();
}
})
}
return id;
}
const addNewDeed = asyncErrorWrapper(async (req, res, next) => {
let information = req.body;
const deedId = await createRandomID();
/*Other Operations...*/
});
I'm having difficulty creating the routes to send to MongoDB.
When I return user, it returns the full database. This goes for using User or 'user'.
User is a model
let User = require('../models/user.model');
User.findById(req.params.id)
.then(user => {
if (!user)
res.status(404).send("data is not found");
else
for(var key in req.body.proposal) {
//res.send(user.proposal)
//res.send(user)
//res.send(User.username)
user.proposal.insertOne(
{
"uid" : req.body.proposal[key].uid,
"clientEmail" : req.body.proposal[key].clientEmail,
"summary" :req.body.proposal[key].summary,
"terms" :req.body.proposal[key].terms,
"form" :req.body.proposal[key].form
} //update
)
}
user.save()
.then(user => res.json(user))
.catch(err => res.status(400).json('Error: ' + err));
})
.catch(err => res.status(400).json('Error: ' + err));
});
Thank you in advanced!
It should be something like this :
let proposalArr = [];
for (const key in req.body.proposal) {
proposalArr.push({
uid: req.body.proposal[key].uid,
clientEmail: req.body.proposal[key].clientEmail,
summary: req.body.proposal[key].summary,
terms: req.body.proposal[key].terms,
form: req.body.proposal[key].form
});
}
user.proposal = proposalArr;
user.save().............
You can't use .insertOne on result of database query, it's a function of mongoose model to insert new document to collection but not to insert new fields to objects. You need to do just like adding new fields to json object using .js code, but mongoose will keep track of object's changes & when you use .save() it can update the document in collection with all those changes.
Instead of two DB calls, you can do that in one call, Check : .findByIdAndUpdate() & try below sample code :
let proposalArr = [];
for (const key in req.body.proposal) {
proposalArr.push({
uid: req.body.proposal[key].uid,
clientEmail: req.body.proposal[key].clientEmail,
summary: req.body.proposal[key].summary,
terms: req.body.proposal[key].terms,
form: req.body.proposal[key].form
});
}
User.findByIdAndUpdate(
req.params.id,
{
proposal: proposalArr
},
{ new: true }
)
.then(user => {
if (!user) res.status(404).send("data is not found");
res.json(user);
})
.catch(err => res.status(400).json("Error: " + err));
I can't save a user to my mongodb, but I can get document. I get the following error each time I try to save a user. I get error from line 27 that's where the email starts from. I have tried other means too but the truth is that I am new to mongodb so I can't tell if the error is from the
code or from the mongodb server. Please help.
error: falior when reseiving data from peer
let User = require('../models/user.model')
const userController = {
//get all the users from the database
getall :(req, res) =>
{
User.find()
.then((users)=>res.json(users))
.catch(err => res.status(400)
.json('Error: ' + err));
/*{field: filter},*/
},
//register users //
register :(req, res) =>{
const {body} = req
const {
firstname,
lastname,
email,
mobile,
password
} = body;
//this is where the error start reporting for
email = email.toLowerCase()
User.find({ email : email}, (err, previousUser) => {
if(err){
res.end({ success : false, message : `Error ${err}`})
}
else
{
if(previousUser.length > 0){
res.end({ success : false, message : 'Already registerd empty'
})
}
else
{
//using user model
const newUser = new User();
//asign values to the user model
newUser.firstname = firstname
newUser.lastname = lastname
newUser.mobile = mobile
newUser.email = email
newUser.password = newUser.generateHash(password)
//save
newUser.save()
.then(()=>res.json('you have succesfuly registerd'))
.catch(err => res.status(400).json('Error: ' + err));
}
}
});
}
}
module.exports = userController
I was so dumb the react component for the code above was not passing the required data for the Fields
I am trying to use the Waterline .native() method to query an item by id in the database. This is what my code looks like:
// Consutruct the query based on type
var query = {};
if (req.param('type') === 'id') {
query = { _id: req.param('number') };
} else {
query = { 'data.confirmationNumber': req.param('number') };
}
Confirmations.native(function(error, collection) {
if (error) {
ResponseService.send(res, 'error', 500, 'Database error.');
} else {
collection.find(query).toArray(function(queryError, queryRecord) {
if (queryError) {
ResponseService.send(res, 'error', 500, 'Database error.');
} else {
if (queryRecord.length > 0) {
ResponseService.send(res, 'success', 200, queryRecord[0]);
} else {
ResponseService.send(res, 'error', 404, 'Your confirmation details could not be found.');
}
}
});
}
});
When the query is 'data.confirmationNumber' it works but if it is '_id' it dows not work. How do I fix this?
if your Id is a ObjectId see this
var ObjectId = require('mongodb').ObjectID;
{_id: new ObjectId(req.param('number') )}
Iniside Model and in attribute define the id field like this
id : {type : 'objectid',primaryKey:true}
When you are querying the code
Here my model name is - QuizModel and the id is coming in the params quizId so here quizId is equal to the _id in the mongodb database
QuizModel.find({_id: QuizModel.mongo.objectId(quizId)})
.then(function(response){
})
.catch(function(error){
});
//router
app.get('/retrieve_report', function(req, res) {
var retrieved = retrieve_report(req, res);
res.render('retrieve_report.ejs', {
'report' : retrieved
});
});
//Load up the report model
var Report = require('../models/report');
console.log('Report ' + Report.schema);
//expose this function to our app using module.exports
//query
module.exports = function(req, res) {
//console.log('param ' + res.send);
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
}
//app.js
var retrieve_report = require('./config/retrieve_report');//which is the above code
I want to return the document to the router so that I can put its information into my view. I tried "res.json(doc), but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');" Everyone says to use a callback function, but aren't I using a callback function here?
As your error says:
but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');"
Means you are trying to send data the twice.
Sample code:
app.get('/retrieve_report', function(req, res) {
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
This should work..