添加对象使用护照重新presents用户到一个数组注册后 [英] adding an object that represents users to an array after signup using passport

查看:98
本文介绍了添加对象使用护照重新presents用户到一个数组注册后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用户名和密码的列表,以便当用户登录他们的凭据,他们可以看到所有的数据每个人看到的,但他们仍然要使用自己的凭证。我想让这样的对象列表网​​友:[{用户名:USER1密码:PASS1},{用户名:用户2,密码:PASS2}] 。本应在注册创建。我虽然 SUBDOCS 会帮助,但我没有得到我想要的东西。我有这样的:

I am trying to make a list of username and passwords so that when a user signs in with their credentials they can see all the data that everyone else sees but they still have to use their own credential. I wanted to make a list of objects like this users : [{username : "user1", password : "pass1"}, {username : "user2", password : "pass2"}]. this should be created on signup. I though subdocs would help but I'm not getting what I want. I have this:

var userlist = new mongoose.Schema({username: String, password : String })
var userSchema = new mongoose.Schema({
    users : [userlist]
})

和我试图将新用户添加到阵列是这样的:

and I attempted to add the new users to the array like this:

app.post("/signup", function(req, res){
    var user = new User;
    user.users.push({username : req.body.username, password : req.body.password})
    user.save(function(err){
        if(err) return handleError(err);
        console.log("success")
    })
    // User.create(users : [{username : req.body.username, password : req.body.password}], function(err, doc){
    //  console.log(doc);

    // })
    res.redirect("/login")
})

这GIVS我这个

> db.users.find().pretty()
{
        "_id" : ObjectId("56ba6219763de71c03199a70"),
        "users" : [
                {
                        "username" : "user1",
                        "password" : "pass1",
                        "_id" : ObjectId("56ba6219763de71c03199a71")
                }
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("56ba6225763de71c03199a72"),
        "users" : [
                {
                        "username" : "user2",
                        "password" : "pass2",
                        "_id" : ObjectId("56ba6225763de71c03199a73")
                }
        ],
        "__v" : 0
}
>

它让单独的文件。我希望它看起来像这样

It's making separate documents. I want it to look like this

{
        "_id" : ObjectId("56ba6219763de71c03199a70"),
        "users" : [
                {
                        "username" : "user1",
                        "password" : "pass1",
                        "_id" : ObjectId("56ba6219763de71c03199a71")
                },                    
                {
                        "username" : "user2",
                        "password" : "pass2",
                        "_id" : ObjectId("56ba6225763de71c03199a73")
                }
        ],
        "__v" : 0
}

有在SUBDOCS中的ObjectID不是对我很重要。我只想把所有的用户在一起,这样当他们去登录,我可以做这样的事情,如果文档是有凭据好,所以继续网站的其他部分。

Having the objectIDs in the subdocs are not so important to me . I just want to group all the users together so that when they go to login I could do something like if the doc is there the credentials are good so continue to other parts of website.

推荐答案

我不知道你是否已经解决,你现在还是没有怀疑,不管这里是回答你的问题。

I am not sure if you have resolved you question by now or not, regardless here is the answer to your problem.

首先,如果你不需要 _id 子文档则指出,在模式相应地,也没有 _id 将被创建。

Firstly if you don't need _id in subdocument then state that in the schema accordingly and no _id will be created.

var userSchema = new Schema({ username: String, password: String},{ _id: false }); 

如果您使用上面的模式用户然后应该没有 _id 子文档字段。

If you use the above schema for user then there should be no _id field in the subdocument.

您应该知道,插入子文档你需要知道的它。如果不提供在插入子文档然后为每个插入一个新的P 租金被创建。在这种情况下,家长包含 _id 用户子文档。如果我有确切的问题,我会去解决它通过以下方式:

You should know that to insert a subdocument you need to know the parent for it. If you don't provide the parent while inserting the subdocument then for each insert a new parent is created. In this case parent contains _id and users subdocument. If I have the exact problem, I would go about solving it the following way:

架构设计保持不变,如下图所示(我将它们命名为不同,以避免混淆):

The schema designs remain the same as shown below (I named them differently to avoid confusion):

var userSchema = new Schema({username: String, password: String},{ _id : false });

var userListSchema = new Schema({
  users: [userSchema]
});

现在我将宣布父模型如下:

Now I will declare the parent model as follow:

var UserList = mongoose.model('UserList', userListSchema);
//see below what list gets assigned. 
var list;

现在让我们假设我有一个路由处理,我想保持在注册时添加的东西的用户,如下所示:

Now let's assume I have a route handler where I would like to keep adding the users upon sign up something as shown below:

app.get("/newuser/:username/:password", function(req, res) {
  //create user model 
  var User = mongoose.model('User', userSchema);
  //load user module, for testing i use params, you can change this to req.body
  var user = new User({username: req.params.username, password: req.params.password});

  //I would like to find the first document in userlists collection 
  UserList.findOne({}, function(err, result) {
    if(err) console.log(err);
    //below if condition is true, if there is one document with users subdoc
    if(result) {
      console.log('Found existing document with users subdocument. Adding user to array.')

       //assign the parent where the subdoc should be inserted to list
       list = result; 

       //there already is a document with subdocument users, so append to it 
       list.users.push(user);

      //save the changed list. 
      list.save(function(err) {
        if (err) console.log(err);
        console.log('User saved.');
      });
    } else {
      console.log('No document found. Creating one and adding  this user to users subdocument.');
      // initialize list model with first ever user 
      list = new UserList({ users: [user] });

      //save the new changed list
      list.save(function(err) {
        if (err) console.log(err);
        console.log('User saved.');
      });
    }
  })
});

完成。现在,当我运行应用程序和访问以下网址首次

Done. Now when I run the app and access the following URL for the first time

http://127.0.0.1:8080/newuser/user1/pass1

userslist 集合看起来如下:

> db.userlists.find().pretty();
{
    "_id" : ObjectId("56c349d6479f5b9b1eaea1c8"),
    "users" : [
        {
            "password" : "pass1",
            "username" : "user1"
        }
    ],
    "__v" : 0
}

我想访问不同参数的方式链接如下图所示:

I would like to access the link with different params as shown below:

http://127.0.0.1:8080/newuser/user2/pass2

和的集合的输出看起来如下:

And the output of the collection looks as follow:

{
    "_id" : ObjectId("56c349d6479f5b9b1eaea1c8"),
    "users" : [
        {
            "password" : "pass1",
            "username" : "user1"
        },
        {
            "password" : "pass2",
            "username" : "user2"
        }
    ],
    "__v" : 1
}

现在我终止应用程序,然后重新运行应用程序和访问以下网址:

Now I terminate the app and then re-run the app and access the following url:

http://127.0.0.1:8080/newuser/user7/pass7

和的集合的输出看起来如下:

And the output of the collection looks as follow:

{
    "_id" : ObjectId("56c349d6479f5b9b1eaea1c8"),
    "users" : [
        {
            "password" : "pass1",
            "username" : "user1"
        },
        {
            "password" : "pass2",
            "username" : "user2"
        },
        {
            "password" : "pass7",
            "username" : "user7"
        }
    ],
    "__v" : 2
}

有你走。我心疼地看到,用户列表集合总是总是总是有一个文件和数组将不断扩大,也许不是一个很好的做法来解决这样的方式您的问题。如果我是你,我会每个用户存储为单个记录然后做组或任何其他汇聚操作。

There you go. I feel bad to see that userlists collection would always always always have one document and its array would keep expanding, maybe not a good practice to solve your issue in this manner. If I were you, I would store each user as a single record and then do the group by or any other aggregation operation.

这篇关于添加对象使用护照重新presents用户到一个数组注册后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆