【问题标题】:Mongodb with Node Js带有 Node Js 的 Mongodb
【发布时间】:2018-12-16 17:39:11
【问题描述】:

如何通过节点 js (mongoose) 执行这个 mongodb 查询。 我有两个具有以下模式的表, 我想从用户表中获取用户名和密码,并从信息表中获取全名。

var infoSchema = mongoose.Schema({ khatam_id:字符串, user_id:字符串, 全名:字符串, });

var usersSchema = mongoose.Schema({ user_id:字符串, 用户名:字符串, 密码:字符串, });

【问题讨论】:

  • 你能具体说明你面临的错误或问题吗,问题不是很清楚问题到底是什么。
  • 假设我有表用户和另一个表信息,信息表有 user_id 我想从信息表中获取所有数据,并带有额外的项目全名,可以从用户表中获取
  • 您仍然可以添加堆栈跟踪或您刚刚在此处编写查询但未描述问题的确切问题,它需要更多信息来解决问题。
  • 添加你的猫鼬模型
  • 您能否使用您在评论中提供的信息编辑问题。

标签: node.js mongodb


【解决方案1】:

我不知道你是否是热门人物,但如果你是,你可以使用它。

userSchema.virtual('infos', 
 {
   ref: 'Info',
   localField: 'user_id',
   foreignField: 'user_id',
 })

假设您将 infoSchema 命名为 Info 模型,mongodb 将其转换为 infos 以防您不知道这就是为什么将虚拟字段称为 infos ref 显然是对 Info 模型的引用 localField 是引用 userSchema 唯一 id 的字段,foreignField 是你在 infoSchema 中引用的字段,它与你提到的 localfield 的唯一值匹配。 最后,连同你的 userSchema 中的所有字段添加这个

{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}

所以当你查询用户时 试一试,它真的派上用场了。 注意:它实际上并没有在数据库中创建一个字段(虚拟的 duh。)它只是填充您的响应对象以进行前端渲染,这实际上更好。

【讨论】:

    【解决方案2】:

    连接 MongoDB:确保 MongoDB 服务在程序执行前正在运行。

     var mongoose = require("mongoose");
        mongoose.connect("mongodb://localhost:27017/your-database");
        mongoose.Promise = global.Promise;
        var connection = mongoose.connection;
        connection.once('open', function() {
           console.log('connected to database);
    
        });
    
        connection.on('error', function() {
          console.error('Mongoose connection error");
    
         });
        process.on('SIGINT', function() {
           mongoose.connection.close(function() {
           console.log('Mongoose connection disconnected due to app SIGINT.');
         });
    
       });
    

    创建用户架构:

    const Schema = mongoose.Schema;
        const usersSchema = new Schema({
         user_id: String,
         username: String,
         fullname: String
        });
    
      const Users = mongoose.model('Users', usersSchema );
    

    像这样运行查询:

     Users.findOne({query})
        .then(function(user){
          // do something
         })
        .catch(function(err){
          // handle error
         }) 
    

    【讨论】:

      【解决方案3】:

      假设您知道如何设置猫鼬并连接您的数据库并且只需要正确的查询,让我与您提供的模型分享我注意到的一些东西。我认为不需要 2 个集合,因为您可以将相同的东西存储在一个集合下,因为它节省了从信息模式查找用户数据的时间。所以用户模式可以是

      var usersSchema = mongoose.Schema({ 
        user_id: String, 
        username: String, 
        password: String,
        khatam_id: String,
        fullname: String
      });
      

      使用以下查询可以获取用户详细信息

      Users.findOne({})
      .then(function(user){
        // do something
       })
      .catch(function(err){
        // handle error
       }) 
      

      与使用聚合查询或猫鼬填充函数相比,这更高效、更快捷。

      如果上述方法不适合你,你可以试试猫鼬填充功能。

      UserSchema = new mongoose.Schema({
          user_id: String,
          password: String,
      },
      // schema options: Don't forget this option
      // if you declare foreign keys for this schema afterwards.
      {
          toObject: {virtuals:true},
          // use if your results might be retrieved as JSON
          // see http://stackoverflow.com/q/13133911/488666
          //toJSON: {virtuals:true} 
      });
      
      UserInfoSchema = new mongoose.Schema({
        user_id: String,
        khatam_id: String,
        username: String,
        fullname: String,
      });
      
      
      // Foreign keys definitions
      
      UserSchema.virtual('userDetails', {
        ref: 'UserInfoSchema',
        localField: 'user_id',
        foreignField: 'user_id',
        justOne: true // for many-to-1 relationships
      });
      
      
      // Models creation
      
      var UserSchema = mongoose.model('UserSchema', UserSchema);
      var UserInfoSchema = mongoose.model('UserInfoSchema', UserInfoSchema);
      
      
      // Querying
      
      UserSchema.find({...})
          // if you use select() be sure to include the foreign key field !
         .select({.... user_id ....}) 
         // use the 'virtual population' name
         .populate('userDetails')
         .exec(function(err, books) {...})
      

      【讨论】:

        【解决方案4】:

        在你的机器上安装猫鼬

        npm install mongoose
        

        导入猫鼬库

        const mongoose = require('mongoose');
        const Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
        

        连接到 mongodb 并为您的表创建架构

        mongoose.connect('mongodb://localhost/myappdatabase');
        
        const usersSchema = new Schema({
         _id: ObjectId,
         user_id: String,
         username: String,
         fullname: String
        });
        
        const Users = mongoose.model('Users', usersSchema );
        

        使用 mongo 查询从“用户”表中查找用户

        Users.find({<here you can write your mongo query>}, function (err, docs) {
          // docs.forEach
        });
        

        【讨论】:

          【解决方案5】:

          你必须使用聚合

          db.users.aggregate([
          {
             $lookup:
               {
                 from: "info",
                 localField: "user_id",
                 foreignField: "_id",
                 as: "userInfo"
               }
          },
          { "$unwind": "$userInfo" },
          ])
          

          【讨论】:

            【解决方案6】:

            您可以使用此查询来获取您想要的那些类型的记录:

            db.users.aggregate([
            {  $lookup: {
                   from: "info",
                   localField: "user_id",
                   foreignField: "user_id",
                   as: "userInfo"}},
            { "$unwind": "$userInfo" }])
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2022-08-18
              • 1970-01-01
              • 2022-11-15
              • 1970-01-01
              • 2015-06-10
              • 2014-03-19
              • 1970-01-01
              相关资源
              最近更新 更多