I'm trying to figure out how you would retrieve the appropriate information on the page when users go to "/users/:name". what I'm trying to do is print out "welcome user2" if user2 logged in and the same for the other users. the way I was thinking of doing it is to pass along the param from "/users/:name" and check if the param is equal to the username value print out that value.(not sure if that is a safe way to do it) how do I cycle through my particular list of objects and compare it to the param?
I get this sent to my jade document
{ list: 'userList', users: [ { password: 'pass1', username: 'user1' }, { username: 'user2', password: 'pass2' }, { username: 'user3', password: 'pass3' } ], address: '14459 70 th st city NY', desc: '3 floors', __v: 0, _id: 56baf181356641f01213295a }
that get's sent because I do this:
app.get("/users/:name", function(req, res){
// console.log(req.params.name)
User.findOne({"users" : { $elemMatch: { username : req.params.name}}}, function(err, doc){
console.log("test ", doc)
res.render("users", {result : doc, name : req.params.name});
})
})
jade:
html
head
body
p= result
p Welcome #{result.users[0].username} #{name} // prints out--> Welcome user1 user2 ||| when user2 signs in
p= result.address
h3= result.desc
a(href="/logout") logout
Then you probably want to go with this, to select appropriate user object for the given param input:
app.get("/users/:name", function(req, res){
// console.log(req.params.name)
User.findOne({"users" : { $elemMatch: { username : req.params.name}}}, function(err, doc){
console.log("test ", doc)
var users = result.users;
var currentUser = {};
for(var i=0;i<users.length;i++)
if(users[i].username === req.params.name)
currentUser = users[i];
res.render("users", {result : doc, user : currentUser });
});
})
Related
I'm making 2 queries to the database.
Right now, if even one of them is undefined, I get the generic 'not found' message that is set up. This is because there's an 'else' set up at every DB query where it responds with 'not found' if a value is undefined
What I want to achieve:
If one of them is null, I want to add the value 'nil'.
Example:
field1: nil,
field2: 'value'
If both are null, then I want it to respond with the previously mentioned 'not found' message.
What's a good approach for this?
I think your goal may be achieved using 1 call to the database by using https://www.mongodb.com/docs/manual/reference/operator/aggregation/switch/ but please provide example document structure and what the expected behavior should be in a bit more detailed way.
[
{
_id: new ObjectId("634989627d163a41b75e1e13"),
name: 'Ashish Jain',
address: 'Delhi'
},
{
_id: new ObjectId("634989cc7d163a41b75e1e14"),
name: '',
address: 'India'
},
{
_id: new ObjectId("634989cc7d163a41b75e1e15"),
name: '',
address: ''
},
{
_id: new ObjectId("634989cc7d163a41b75e1e16"),
name: 'Ash',
address: ''
}
]
This is my existing data in the local database.
Following is my Node.js code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("test");
var all_docs = dbo.collection("ccn1").find({}).toArray(function(err, result) {
if (err) throw err;
for (i in result){
if(result[i]['name'] && result[i]['address']) {
console.log("name: " + result[i]['name'])
console.log("address: " + result[i]['address'])
}
else if (result[i]['name'] && !result[i]['address']){
console.log("name: " + result[i]['name'])
console.log("address: nil")
}
else if (!result[i]['name'] && result[i]['address']){
console.log("name: nil")
console.log("address: " + result[i]['address'])
}
else {
console.log("Not Found")
}
console.log()
}
db.close();
});
});
What you are seeing below the output:
(base) ashish#ashishlaptop:~/Desktop/software/node$ node "Hello World Script For MongoDB Local.js"
name: Ashish Jain
address: Delhi
name: nil
address: India
Not Found
name: Ash
address: nil
I want to create a social network thus allowing users to send and interact with frind requests. As of now I have created the register, log-in and "search for other users function".
When I find and select another user, I display their user-info and have created a "Add friend" button.
Can anyone help me in a direction of the creation of the "Add friend" option? I have looked around for some time now, and not been able to find the correct solution. Below I have attached my UserSchema and route for finding users:
//User Schema
const UserSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
password: {
type: String,
required: true
},
},{ collection: 'Users' });
//Get single user based on ID
router.get('/user/get:id', ensureAuthenticated, function (req, res) {
MongoClient.connect(DBUri,{useUnifiedTopology: true }, function (err, db) {
let dbo = db.db(DBName);
const query = {_id: objectId(req.params.id)}
dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
if (err) throw err;
res.render('../View/findFriend', {
resultTasks: resultTasks
});
db.close();
});
});
});
You can add something like this in your user schema:
friends: [{ type : ObjectId, ref: 'User' }],
OR
friends: userSchema
Take the one which suits you.
What that will do is add an array to the user, Then you can store IDs of friends.(Who are other users, hence the ref: 'User')
Then, When you have to fetch users you can do:
User.find(<ID or whatever you have to find Users>).populate('friends')
Also, To push a new friend simply use: user.friends.push(newFriend._id)
const UserSchema = new Schema(
{
referrals: {
ref: 'User',
type: [mongoose.Schema.Types.ObjectId],
},
referredBy: {
ref: 'User',
type: mongoose.Schema.Types.ObjectId,
},
}
);
I want Mongoose to find users who have current user _id in referredBy reference.
In other words, eg: find all users who have '_IDOfSpecificUser' in their referredBy field and put all the found users in the array of referrals where user's _id is '_IDOfSpecificUser'.
How can I handle that in mongoose?
Simplest is using find
User.
find({ "referredBy" : "xxxxxxxxxxxx" }).
exec(function (err, users) {
if (err) return handleError(err);
console.log('The users are an array: ', users);
});
Refer to https://mongoosejs.com/docs/populate.html
If you want to convert bellow function to static method inside UserSchema, please refer to this https://mongoosejs.com/docs/api.html#schema_Schema-static and https://mongoosejs.com/docs/2.7.x/docs/methods-statics.html
I am using mongodb and I want to be able to edit a document and reinsert it WITHOUT duplicates. So far i have tried collection.findAndModify() but I couldn't get that to work. I have a collection like this:
UserProfiles = [
{
userProfileID: 1,
firstName: 'Austin',
lastName: 'Hunter',
email: 'ahun.....com',
token: '',
platform: '',
password: 'incorrect',
companyProfileID: 1,
authentication: '',
UserTopics: [
I want to be able to do this:
1 - grab the profile out of the object via searching for email match.
2 - when the email matches, edit the token and platform item.
3 - then put the document back in with no duplicates. So I can't just insert it again because that duplicates it.
Can anyone help me out on figuring this out?
Code:
function registerUser(email, token, platform) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
collection.findAndModify({
query: { email: email },
update: { token: token, platform: platform }
});
db.close();
modelname.findOneAndUpdate({ email: var_email}, { $set: { token: var_token, platform: var_platform}}, { new: true }, function(err, doc)
{
//doc here has updated document, in case you need it.
});
var_email etc. is your variable name and email is field name in
database.
{ new: true } - This part is used to fetch updated document, you can chose to not have this in your code but then you wont get updated document in response.
How can we automatically create a second user when the user registers (the first user) from a form generated using the useraccounts:core package?
Running a Accounts.createUser from within Accounts.onCreateUSer causes an error Exception while invoking method 'ATCreateUserServer' TypeError: Cannot read property '_id' of undefined
Accounts.onCreateUser(function(options, user) {
// Create Primary User
if(!user.type) {
// Set user.type as 'user'
user.type = 'user'
// Create Secondary User
Accounts.createUser({
username: options.profile.slaveName,
password: options.profile.slaveName,
type: 'slave',
profile: {
firstName: user.profile.firstName,
lastName: user.profile.lastName
}
})
user.profile = options.profile
return user
}
// Create Secondary User
if(user.type == 'slave') {
user.profile = options.profile
return user
}
});
It looks to me like you're conflating the user argument and the options argument. For instance, the type field comes in through the options argument, not user.
The following code worked for me:
Accounts.onCreateUser(function(options, user) {
// Create Primary User
if(!options.type) {
// Set user.type as 'user'
options.type = 'user'
// Create Secondary User
Accounts.createUser({
username: options.profile.slaveName,
password: options.profile.slaveName,
type: 'slave',
profile: {
firstName: options.profile.firstName,
lastName: options.profile.lastName
}
});
user.profile = options.profile
return user
}
// Create Secondary User
if(options.type == 'slave') {
user.profile = options.profile
return user
}
});
I then tested like so:
// console
Accounts.createUser({username: "guest", password: "guest", profile: {slaveName: 'guestslave', firstName: "Greatest", lastName: "Ever"}})
Meteor.users.find({username: {$regex: 'guest'}}).fetch()
> [returned two user objects]