How to use object id that give reference in nodejs mongodb - node.js

There is no another error but I want to know just one thing.How to use that give reference in User schema object _id it means location_id how to use when I add new User.
User Schema :
var userSchema = Mongoose.Schema({
name:{type: String,require:true},
surname: {type: String,require:true},
tel: {type: String,require:true},
age: {type: String,require:true},
mevki_id: {type: String,require:true},
location_id: { type: Mongoose.Schema.Types.ObjectId, ref: 'locations' }
});
Location schema:
var LocationSchema = Mongoose.Schema ({
il: {type: String, require:true},
ilce: {type:String, require:true}
});
UserController -- I add user here
this.createUser = function(req, res) {
var la=new Location({il:'istanbul',ilce:'camlica',location_id:la._id}).save(function (err) {
if (err) return handleError(err);
});
var user = new User({
name:'akif',surname:'demirezen',tel:'544525',age:'45',mevki_id:'2',
}).save(function (err) {
if (err) return handleError(err);
res.send(JSON.stringify(job));
});
}

There are several errors in your code. For example, the require property should be required.
Other problem is that you are setting the location_id value of la with a reference to la, that at that time has not been yet assigned a value.
Mongo will automatically create a field called _id: ObjectId on all your objects. Try this:
this.createUser = function(req, res) {
var la = new Location({
il:'istanbul',
ilce:'camlica',
}).save(function (err, location) {
if (err) return handleError(err);
var user = new User({
name:'akif',
surname:'demirezen',
tel:'544525',
age:'45',
mevki_id:'2',
location_id: location._id
}).save(function (err, user) {
if (err) return handleError(err);
// Warning: AFAIK job does not exist, should it be user?
res.send(JSON.stringify(job));
});
});
}

Related

Mongoose: Using the same schema in two separate arrays

I have two schemas, defined as following:
var userSchema = new Schema({
email: String,
name: String,
role: String,
password: String
})
var raceSchema = new Schema({
date: Date,
name: String,
location: String,
time: String,
register: String,
participants: [{ type: Schema.Types.ObjectId, ref: 'User'}],
registered_participants: [{ type: Schema.Types.ObjectId, ref: 'User'}],
})
As you can see, I reference the first schema twice in the second schema. If I add a reference to a user in one of the lists, everything is fine. But when I add a reference to the same user to the other list I get the following error: Cast to [undefined] failed for value
What causes this error? Is it related to the fact that the same schema is used twice in the second schema?
Edit:
I get the error when I call the following Express endpoint:
app.post('/race/:id/registered', passport.authenticate('jwt', { session: false}), (req, res) =>
Race.findOne({ _id: req.params.id }, function (err, race) {
if (err) return res.json({'Error': err})
if (!race) return res.json({'Error': 'Race not found'})
race.registered_participants.push(req.user)
race.save(function (err, updatedRace) {
if (err) return res.json({'Error': err})
res.send(updatedRace)
})
})
)
Edit 2: The model definitions:
var User = mongoose.model('User', userSchema);
var Race = mongoose.model('Race', raceSchema);
Try using findByIdAndUpdate in your POST method instead:
app.post('/race/:id/registered', passport.authenticate('jwt', { session: false}), (req, res) =>
Race.findByIdAndUpdate(req.params.id,
{ $push: { registered_participants: req.user } },
function (err, race) {
if (err) return res.json({'Error': err})
res.send(race)
})
)

Mongo db, how to give object _id another collection's document

I have 2 collections called User and Location. In User, there is a location _id and this is an Object. Id also references the location collection. My question is what did I do wrong? When I call getUser function I want to see user information and the user's location information. What I need to do ?
User Schema
module.exports = (function userSchema() {
var Mongoose = require('mongoose');
var userSchema = Mongoose.Schema({
name: {
type: String,
require: true
},
surname: {
type: String,
require: true
},
tel: {
type: String,
require: true
},
age: {
type: String,
require: true
},
mevki_id: {
type: String,
require: true
},
location_id: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'locations'
}]
});
var collectionName = 'users';
var User = Mongoose.model(collectionName, userSchema);
return User;
})();
User Controller
function userController() {
var User = require('../models/UserSchema');
this.createUser = function (req, res, next) {
var name = req.body.name;
var surname = req.body.surname;
var tel = req.body.tel;
var age = req.body.age;
var mevki_id = req.body.mevki_id;
var lok_id = req.body.lok_id;
User.create({
name: name,
surname: surname,
tel: tel,
age: age,
mevki_id: mevki_id,
lok_id: lok_id
}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'result': result,
'status': 'successfully saved'
});
}
});
};
this.getUser = function (req, res, next) {
User.find()
.populate('lok_id')
.exec(function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'USERS': result
});
}
});
};
return this;
};
module.exports = new UserController();
First, your schema is wrong:
var userSchema = new Mongoose.Schema({
// ...
location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' }
})
Second, in your schema the last field name is location_id while in your controller, you change it to lok_id.
So, fix this:
User.create({
// ...
location_id: lok_id
}
and this:
User
.find()
.populate('location_id')
UPDATE
In your json the last field name is location_id, therefore, fix this too:
this.createUser = function (req, res, next) {
// ...
var lok_id = req.body.location_id;
}

Create an association through a single form Mongoose/express

Through a single form I'm trying to build a game object that consists of a 'game_name', and a 'game_length', and a ref association by ObjectId to a 'player'. What I have is building both objects but the player is not being saved in the players array in the Game model. Thanks for any help in advance.
Schema and Models
Game Schema/Model
var gameSchema = new mongoose.Schema({
course_name: String,
game_length: Number,
players: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Game'
}],
created: {type: Date, default: Date.now}
})
var Game = mongoose.model('Game', gameSchema);
Player Schema/Model
var playerSchema = new mongoose.Schema({
player_name: String,
})
var Player = mongoose.model('Player', playerSchema);
Post Route
app.post('/games', function(req, res){
Game.create(req.body.game, function(err, newGame){
if (err) console.log(err);
Player.create(req.body.player, function(err, newPlayer){
if (err) console.log(err);
newGame.players.push(newPlayer);
})
res.redirect('games');
})
})
It looks like you just need to call .save:
app.post('/games', function(req, res){
Game.create(req.body.game, function(err, newGame){
if (err) console.log(err);
Player.create(req.body.player, function(err, newPlayer){
if (err) console.log(err);
newGame.players.push(newPlayer);
newGame.save(function(err) {
if (err) return console.log(err);
// saved!
res.redirect('games');
});
})
})
})

Mongoose return populated array after save

I am trying to return an updated object as JSON, where the update was to set an array of objectIDs. I want the returned objected to have that array populated. For example, I have the following (simplified) model:
var UserSchema = new mongoose.Schema({
username: {type: String, unique: true, required: true},
friends: [{type: mongoose.Schema.Types.ObjectId, ref: 'User'}]
});
In my controller, I have:
exports.saveFriends = function(req, res) {
User.findById(req.params.user_id, function(err, user) {
// req.body.friends is JSON list of objectIDs for other users
user.friends = req.body.friends
user.save(function(err) {
user.populate({path: 'friends'}, function(err, ticket) {
if (err) {
res.send(err);
} else {
res.json(user);
}
});
});
});
}
This does in fact save the array properly as ObjectIDs, but the response user always shows "[]" as the array of friends.
Anyone see my issue?

Mongoose populate issue - array object

My schema is as below
Sectionschema
var SectionSchema = new Schema({
name: String,
documents : {
type : [{
type: Schema.ObjectId,
ref: 'Document'
}]
}
}
}
DocumentSchema
var DocumentSchema = new Schema({
name: String,
extension: String,
access: String, //private,public
folderName : String,
bucketName : String,
desc: String
});
Api.js
exports.section = function(req, res, next, id) {
var fieldSelection = {
_id: 1,
name: 1,
documents : 1
};
var populateArray = [];
populateArray.push('documents');
Section.findOne({
_id: id
}, fieldSelection)
.populate(populateArray)
.exec(function(err, section) {
if (err) return next(err);
if (!section) return next(new Error('Failed to load Section ' + id));
// Found the section!! Set it in request context.
req.section = section;
next();
});
}
If I go this way, I have
the 'documents' object is []. However if I remove, "populateArray.push('documents');" then I get documents:['5adfsadf525sdfsdfsdfssdfsd'] -- some object Id (atleast)
Please let me know the way I need to populate.
Thanks.
Change your query to
Section.findOne({
_id: id
}, fieldSelection)
.populate('documents.type')
.exec(function(err, section) {
if (err) return next(err);
if (!section) return next(new Error('Failed to load Section ' + id));
// Found the section!! Set it in request context.
req.section = section;
next();
});
and this works. You need to give the path to populate.
If you just want "documents" in your schema pointing to Array of ObjectID which you will populate later. then you can use this.
var SectionSchema = new Schema({
name: String,
documents : [{
type: Schema.ObjectId,
ref: 'Document'
}]
});
And use the following to populate it
Section.findOne({
_id: id
}, fieldSelection)
.populate('documents')
.exec(function(err, section) {
if (err) return next(err);
if (!section) return next(new Error('Failed to load Section ' + id));
// Found the section!! Set it in request context.
req.section = section;
next();
});

Resources