Mongoose not saving document completely - node.js

I am trying to save data to my mongo db using mongoose. But unfortunately I am not able to save it completely. However it creates a data array but defaults like company name etc. are not saving. However these values are not available in requested body
I am using:
var seller = new sellers(req.body);
seller.save(function (err) {
if (err) {
return res.status(500).send('An user with this email id or mobile number already exist');
}
res.status(200).send('You have successfully registered');
})

In this case you could use a pre save hook to set an object as the default in your array:
userSchema.pre('save', function(next) {
if (this.data.length == 0) {
var default = {
fieldName: 'Company Name',
fieldValue: 'No Information Provided',
// etc.
};
this.data.push(default);
}
next();
});

Related

How to save schema data to another collection from route function

Hello I have less idea in express route as I am new in backend with mongodb.
In the route below I am verifying email by resetting a schema value to true. Now I want to copy the new schema details to another existing collection. How can I do that ?
router.get('/:adminId/verifyAdmin',function(req,res){
console.log('request recieved');
Admin.findOne( {_id: req.params.adminId })
.exec()
.then(admin => {
const Thing = mongoose.model(admin.companyName);
const emailTokenn = req.query.id;
//console.log(emailTokenn);
Thing.updateOne( { emailResetTokenn: emailTokenn },{ $set: { verified: true }},(err) =>{
if(!err){
return res.redirect('https://localhost:3000/fw18/index.html');
}
else{
throw err;
}
});
});
});
Here I want to pass/copy/save Thingcollection details to existing collection name users in my db.
EDIT:- Tried this but getting error export :- const User = mongoose.model('User');
Thing.updateOne( { emailResetTokenn: emailTokenn },{ $set: { verified: true }},(err) =>{
if(!err){
//add Thing Schema to Users collection
Thing = mongoose.model(admin);
var copy = mongoose.model('admin', admin,'User');
admin.save(function(err){});
return res.redirect('https://s3.ap-south-1.amazonaws.com/fw18/index.html');
}
Error:-
MissingSchemaError: Schema hasn't been registered for model correct me .
Http is a stateless protocol. To maintain state of the application you can use
1) session
2) cookies and
3) query string.
On your case, you can handle using session.
Store information to the session and get stored information from different routes.

Post same objectID in to different table

I'm trying to post a data in my user then at the same time, post the _id of my user as a reference id in my donation table.
After I posted my data in the users table like this:
var User = require('../models/user');
var Blooddonation = require('../models/blooddonation');
router.post('/createBlooduser',function(req, res) {
var user = new User();
user.user_lastname = req.body.user_lastname;
user.status= "initial";
user.save(function(err) {});
});
How can I get the _id of the posted data and make a reference id in my donation table? Something like this:
**users.json**
{
_id:ObjectId("5c7e591eee959272cc5768cb"),
user_lastname:"Jhonson",
status:"initial"
}
**blooddonations.json**
{
donor_id:ObjectId("5c7e591eee959272cc5768cb")
}
The _id property is actually created as soon as you create new instance with a statement like new User(). So you can actually access that value before it's even stored in the collection, or at any time after instance creation really:
router.post('/createBlooduser',function(req, res) {
var user = new User();
user.user_lastname = req.body.user_lastname;
user.status= "initial";
user.save(function(err) {
if (err) throw err; // or really handle better
// You can also just create() rather than new Blooddonation({ donor_id: user._id })
Blooddonation.create({ donor_id: user._id }, function(err, donor) {
// check for errors and/or respond
})
});
});
Of if you might just want access to other properties that might "default on save", then you can access in the callback from save() or create():
router.post('/createBlooduser',function(req, res) {
User.create({
user_lastname: req.body.user_lastname;
status: "initial"
}, function(err, user) { // this time we pass from the callback
if (err) throw err; // or really handle better
Blooddonation.create({ donor_id: user._id }, function(err, donor) {
// check for errors and/or respond
});
});
});

Mongoose $addToSet return new list entrys

I have a question working with mongoose 4.0.1
I am trying to add new picture objects to an array inside a model. This is the code of my endpoint that is actually doing the job:
// Add new images
exports.pictures = function(req, res) {
Incident.findByIdAndUpdate(
req.params.id,
{$addToSet: {"pictures": {$each: req.body}}},
{new: true},
function(err, incident) {
if (err) { return handleError(res, err); }
return res.send(201).json(incident.pictures);
}
);
};
The problem: The callback object (incident) stores all information of the model which was found and updated. But I want to return only the new array entries which were created.
How can I receive the actual changes of the operation instead of the whole object that is storing the pictures array?
I solved the problem by creating a new schema for pictures and adding a reference to the incident model.
The endpoint changed as well:
Create new picture instances for a array of pictures
Find incident by id
Save the references of the picture instances to a array inside the incident
Return the id of the picture instances
var _ = require('lodash');
// Add new images
exports.pictures = function(req, res) {
Picture.create(req.body, function(err, pictures) {
if (err) { return handleError(res, err); }
Incident.findByIdAndUpdate(
req.params.id,
{$addToSet: {"pictures": {$each: pictures}}},
function(err) {
if (err) { return handleError(res, err); }
var pictureIds = _.map(pictures, '_id');
return res.status(201).json(pictureIds);
}
);
});
};

Mongoose middleware access other collection

I am using 'pre' 'save' middleware to create for a 'user' document a corresponding 'userObjects' document.
So there is users collections and userObjects.
And when new user is inserted a userObjects document should be inserted too.
I am trying to use the 'pre' middleware, somehow like this :
//before inserting a new user
Users.pre('save', function(next) {
var UserObjects = db.model('userObjects');
userObjectsIns = new UserObjects({
'userID': this._id,
'myObjects':[],
});
userObjectsIns.save( function(err) {
if (err) console.log("ERROR while saving userObjectsIns: " + err);
next()
})
});
The obvious problem, is that db doesn't exists. How can I reach 'userObjects' collection from within this pre middleware?
You can access other models via the model method of the this doc instance:
Users.pre('save', function(next) {
var UserObjects = this.model('userObjects');
userObjectsIns = new UserObjects({
'userID': this._id,
'myObjects':[],
});
userObjectsIns.save( function(err) {
if (err) console.log("ERROR while saving userObjectsIns: " + err);
next()
})
});

Pre-populating documents using Mongoose + Express

I am new to Node+Mongoose, and am currently in the process of creating an API using KeystoneJS. I've managed to populate all posts with the author's email and name. My question is, is there a way to populate the post with author everytime, possibly with some middlewear, without having to rewrite it in each method where I retrieve posts? My goal is to not have multiple instances of populate('author', 'email name') scattered throughout the code. For instance, in the future, I'd like to include the author's profile photo url as well, and I'd prefer to be able to make that change in a single place, that will then be reflected in every place that I retrieve posts.
Current implementation:
Post.model.find().populate('author', 'email name').exec(function (err, posts) {
if (!err) {
return res.json(posts);
} else {
return res.status(500).send("Error:<br><br>" + JSON.stringify(err));
}
});
Post.model.findById(req.params.id).populate('author', 'email name').exec(function (err, post) {
if(!err) {
if (post) {
return res.json(post);
} else {
return res.json({ error: 'Not found' });
}
} else {
return res.status(500).send("Error:<br><br>" + JSON.stringify(err));
}
});
You can create model using statics. This is example of methods for schema
PostSchema.statics = {
getAll: function(cb) {
return this
.find()
.populate('author', 'email name')
.exec(cb);
}
}
You still should use "populate", but it will be in schema file, so you will not care about it in future

Resources