how to fix mongoose array in node - javascript

i'm trying to push objects into my mongodb db.
I'm able to view said data when pushed in my console.log. but they arent pushed into the db at all.
Below is my app.js code..
const userSchema = new mongoose.Schema({
email : String,
password: String,
selectedPet : [String]
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
app.post("/prototype",(req, res) =>{
var animalSelected = [];
animalSelected.push = req.body.selectedPet;
console.log(req.user.id, animalSelected);
User.findById(req.user.id, function(err, foundUser){
if (err){
console.log(err);
} else {
if (foundUser){
foundUser.selectedPet = animalSelected;
foundUser.save(function(){
res.redirect("/proto")
});
}
}
});
});

Related

Turn String into Mongoose Model

I'm learning how to make Mongoose models in Express right now and was wondering if there is a way to convert a string into a matching model.
For instance, if I have a Mongoose model called "User" and a variable like const name = "User", is there a way to convert the string "User" into a User model? Specifically, is there a way to make the following code work?
const name = 'User';
name.findByIdAndUpdate()
Suppose this was the model:
const schema = new mongoose.Schema({ name: 'string' });
const User = mongoose.model('User', schema);
const name = 'User';
Now use the model to construct a document:
const user = new User({ name });
user.save(function (err) {
if (err) return handleError(err);
// saved!
});
or
User.create({ name }, function (err, user) {
if (err) return handleError(err);
// saved!
});
or
const user = await User.create({ name });
Now you can use:
User.findByIdAndUpdate(user.id, { ... }, { ... });
Reference: https://mongoosejs.com/docs/models.html.

stuck in : Cannot read property 'push' of undefined

This is my first project and my first post.
I'm creating a betting website to use between friends and I'm stuck with this error : Cannot read property 'push' of undefined
I guess its something small to make its work again?
Any sugestions?
router.post("/bets", function(req, res){
var betHome = req.body.betHome;
var betAway = req.body.betAway;
var matchid= "5e84bd729511b98c34101a9e"
var author = {
id: req.user._id,
username: req.user.username
}
var newBet = {bet:[betHome,betAway],author:author, matchid:matchid}
Bet.create(newBet, function (err, newlyCreated){
if(err){
console.log(err);
} else {
Match.betsList.push(newBet)
res.redirect("/bets");
console.log(newBet)
}
})
})
module.exports = router;
Database Schema
You can't push in Model directly first create an object of Match Model then push.
router.post("/bets", function(req, res){
var betHome = req.body.betHome;
var betAway = req.body.betAway;
var matchid= "5e84bd729511b98c34101a9e"
var author = {
id: req.user._id,
username: req.user.username
}
var newBet = {bet:[betHome,betAway],author:author, matchid:matchid}
Bet.create(newBet, function (err, newlyCreated){
if(err){
console.log(err);
} else {
var match = new Match({}); // new Schema
match.betsList.push(newlyCreated._id)
res.redirect("/bets");
console.log(newBet)
}
})
})
module.exports = router;

Mongoose findOne() callback returning null

I'm trying to find a user in my node app with mongoose by using
var User = require('../app/models/user');
function mongoTest() {
var publicAddress = "0x8a6be8979340faa30020b0c1f617d8fd4309679f";
User.findOne({"publicAddress": publicAddress}, (err, user) => {
if (err) {
res.status(500).send(err)
} else {
console.log(user);
}
});
}
and err and user always return null. From other questions here (this and this), this usually seems to be related to mongoose pluralising collections. However, I don't think that's my issue because my users.js has
module.exports = mongoose.model('User', userSchema);
// Have also tried module.exports = mongoose.model('User', userSchema, 'User');
For completeness, users.js is
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// Define the schema for our user model
var userSchema = mongoose.Schema({
local: {
username: String,
password: String,
pictureCaption: String,
publicAddress: String,
contractAddress: String
}
});
Finally, I'm sure that public address exists because I can see it in the mongoDB with Robo 3T.
In your userSchema the publicAddress is part of local object.
var userSchema = mongoose.Schema({
local: {
username: String,
password: String,
pictureCaption: String,
publicAddress: String,
contractAddress: String
}
});
You are trying to find an object with publicAddress but it's actually inside the local object. So you should edit the query as follows to get the result.
User.findOne({"local.publicAddress": publicAddress}, (err, user) => {
if (err) {
res.status(500).send(err)
} else {
console.log(user);
}
});

Mongoose save doesn't work "id is not defined"

It's my first time using Mongoose and the save function is not working for me...
On user model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = mongoose.model('User', {
name: Schema.Types.Mixed,
gender: String,
email: String
});
module.exports = User;
On my user controller file:
// Create a user
router.post('/', function(req, res) {
var user = new User(req.body);
user._id = mongoose.Types.ObjectId();
user.save(function(err) {
if (err) {
return res.status(500).json({
error: "Error creating user: " + err
});
}
return res.status(200).end();
});
});
I tried everything but I can't save the user object to the database: "id is not defined"
On the db the _id is a ObjectId.
Thanks.
mongoose.model receives collection name and a Schema as arguments, not an regular object.
So you should use the following code instead:
var schema = new mongoose.Schema({
name: Schema.Types.Mixed,
gender: String,
email: String
});
var User = mongoose.model('User', schema);
maybe we can change the code structure && remove "user._id", test please this code :
*model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: Schema.Types.Mixed,
gender: String,
email: String
});
module.exports = mongoose.model('User', UserSchema);
*controller file:
// Create a user
router.post('/', function(req, res) {
var user = new User(req.body);
user.save(function(err) {
if (err) {
return res.status(500).json({
error: "Error creating user: " + err
});
}
return res.status(200).end();
});
});

not able to store the data to mongoDB

I am trying since 3 hours to store the data from html form to mongodb using noddejs.
while clicking on submit it shows another page which returns the data which has been submitted in json format but it is not being stored in database.
This is my app.js:
app.use(serveStatic(__dirname+"/index.html")).listen(8080);
var mongoUri = 'mongodb://localhost/test';
//Note that I am changing the dbname and trying to store data in different //db will also shows the same error
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database at ' + mongoUri);
});
console.log("connection successfull");
app.use(express.bodyParser());
app.use(express.static(__dirname + "/" ));
app.use(bodyParser.urlencoded({extended:true}));
app.post('/InquiryDetails', function(req,res){
res.json(req.body);
console.log(req.body);
});
require('./models/InquiryDetails');
app.listen(4000);
console.log('Listening on port 4000...');
this is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myskyllSchema = new Schema({
name: String,
email: String,
state: String,
country: String,
school: String,
profession: String,
phone: Number
});
mongoose.model('InquiryDetails', myskyllSchema);
This is my controller:
var mongoose = require('mongoose'),
InquiryDetails = mongoose.model('InquiryDetails');
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
Any help will be appreciated.
Just replace the code in app.js :
app.post('/InquiryDetails', function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
res.send(req.body);
});
});
instead of :
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
The reason is controller was unable to load and method add is not registered with post method. Now it is working.

Categories