简体   繁体   English

Mongodb和Node Js

[英]Mongodb with Node Js

How can i execute this mongodb query through node js (mongoose). 我如何通过节点js(mongoose)执行此mongodb查询。 i have two tables with the follwoing schemas, i want to fetch username and password from users table and fetch full name from the info table. 我有两个具有以下架构的表,我想从用户表中获取用户名和密码,并从信息表中获取全名。

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

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

install mongoose in your machine 在机器上安装猫鼬

npm install mongoose

import mongoose lib 进口猫鼬库

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

connect to mongodb and create schema for your table 连接到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 );

Find user from "Users" table using mongo query 使用mongo查询从“用户”表中查找用户

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

you have to use aggregate 您必须使用汇总

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

i don't know if you're a hot shot but if you are you can use this. 我不知道您是否是热门人物,但如果您可以使用此功能。

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

Assuming u name you're infoSchema as Info model ,mongodb converts it to infos in case you didn't know thats why the virtual field will be called as infos ref obviously a reference to Info model localField is the field referring the userSchema unique id and foreignField is the field u are referring in the infoSchema which matches the unique value that localfield u mentioned . 假设您将您命名为infoSchema作为Info模型,mongodb会将其转换为infos以防万一您不知道为什么将虚拟字段称为infos ref显然是对Info模型localField的引用是引用userSchema唯一ID和foreignField是您在infoSchema中引用的字段,该字段与您提到的localfield唯一值匹配。 Finally, along with all the fields in your userSchema add this 最后,连同userSchema中的所有字段一起添加

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

so when u query for user Give it a shot it really comes in handy. 因此,当您查询用户试穿时,它确实派上用场。 Note: it doesn't actually create a field in the database (virtual duh.) it just populates your response object for front end rendering which is actually better. 注意:它实际上并没有在数据库中创建一个字段(虚拟duh。)它只是填充您的响应对象以进行前端渲染,实际上效果更好。

Connect to MongoDB: Make sure MongoDB service is running before the program execution. 连接到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.');
     });

   });

create user schema : 创建用户架构:

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

  const Users = mongoose.model('Users', usersSchema );

Run Query like this: 像这样运行查询:

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

You can use this query to get those types of records what you want: 您可以使用此查询来获取所需的记录类型:

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

Assuming you know how to set setup mongoose and connect your database and only need the correct query let me share something i noticed with the models you provided. 假设您知道如何设置安装猫鼬和连接数据库,并且只需要正确的查询,就让我与您提供的模型分享一些我注意到的内容。 I don't think there is a need for 2 collections as you can store the same thing under one collection because it saves the time for lookup for the user data from info schema. 我认为不需要2个集合,因为您可以在一个集合下存储同一内容,因为这样可以节省从信息架构中查找用户数据的时间。 So user schema can be 因此用户架构可以是

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

And using the following query you can get the user details 并使用以下查询您可以获得用户详细信息

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

This is much more efficient and faster compared to using aggregate queries or mongoose populate functions. 与使用聚合查询或猫鼬填充函数相比,此方法效率更高,速度更快。

If the above method is not suitable for you you can try the mongoose populate function. 如果以上方法不适合您,则可以尝试使用猫鼬填充功能。

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) {...})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM