我想知道是否有一种方法让用户使用用户名或电子邮件登录 我搜索了很多次但没有找到工作方法.我不知道如何做到这一点,请尽可能以最简单的方式帮助.这是我的用户架构的样子:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
fullname: String,
username: { type : String , lowercase : true , unique: true , required: true, minlength: 3, maxlength: 10},
email: String,
password: String,
mobile: String,
gender: String,
profession: String,
city: String,
country: String,
joining: {type: Date, default: Date.now}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Run Code Online (Sandbox Code Playgroud)
添加信息:我正在使用nodejs.任何帮助都非常感谢.日Thnx
编辑
最小的复制回购
在代码中解释比在英语中更容易.下面的代码可以工作,但感觉就像是一个更简单,更MongoDBy/mongoosy方式...
// recipeModel.js, relevant part of the schema
equipments: [{
_id: {
type: Schema.Types.ObjectId,
ref: 'equipments',
},
quantity: {
type: Number,
required: true,
},
}],
// recipeController.js
const equipmentsWorkaround = recipe => Object.assign({}, recipe.toObject(), {
equipments: recipe.toObject().equipments.map(equip => ({
quantity: equip.quantity,
name: equip._id.name,
_id: equip._id._id,
})),
})
const getItem = (req, res, next) => {
Recipes.findById(req.params.id)
.populate('equipments._id')
.then(equipmentsWorkaround) // <--- ugh ...
.then(recipe => res.json(recipe))
.catch(next)
}
Run Code Online (Sandbox Code Playgroud)
我知道如何ref在猫鼬中做一个"常规" ,但是我在这里甚至可能在mongo中吗?
期望的结果:
equipments: [
{
quantity: 1,
name: …Run Code Online (Sandbox Code Playgroud) mongoose express mongodb-query mongoose-populate mongoose-schema
我创建了一个Mongoose Schema并为Model添加了一些名为Campaign的静态方法.
如果我是console.log Campaign我可以看到它上面的方法.问题是我不知道在哪里添加这些方法,以便Typescript也知道它们.
如果我将它们添加到我的CampaignModelInterface,它们仅适用于模型的实例(或者至少TS认为它们是).
campaignSchema.ts
export interface CampaignModelInterface extends CampaignInterface, Document {
// will only show on model instance
}
export const CampaignSchema = new Schema({
title: { type: String, required: true },
titleId: { type: String, required: true }
...etc
)}
CampaignSchema.statics.getLiveCampaigns = Promise.method(function (){
const now: Date = new Date()
return this.find({
$and: [{startDate: {$lte: now} }, {endDate: {$gte: now} }]
}).exec()
})
const Campaign = mongoose.model<CampaignModelInterface>('Campaign', CampaignSchema)
export default Campaign
Run Code Online (Sandbox Code Playgroud)
我也试过通过Campaign.schema.statics访问它,但没有运气.
任何人都可以建议如何让TS了解模型中存在的方法,而不是模型实例?
假设我有3个node.js项目(1个应用后端,1个应用管理员后端,1个分析api)。在每个项目中,我都有一个模型架构调用贷款。
{
attributes: {
userId: { type: String, required: true, index: true, ref: 'users', comment: '??id' },
amount: { type: Number, required: true, min: 0},
totalAmount: { type: Number, required: true, min: 0},
penaltyInterest: { type: Number, min: 0, required: true, default:
0 }
}
methods: {
getFee () {//some calculation ops
}
save() {//some db ops
}
sendTo3rdComponent() {//some network ops
}
}
Run Code Online (Sandbox Code Playgroud)
该模型具有:一些方法,它是模式设计,api实现。如何在其他两个项目中重复使用它。
对于多个项目重用设计和api是非常重要的。
通常,我们通过将其作为npm包公开来重用该组件。但是,此组件具有自己的数据库操作和网络操作。是否可以将其作为npm软件包?
另一种选择是像eggjs
那么,复制粘贴旁边的优雅解决方案是什么?
我已经开始学习Node.js了,有一点让我感到困惑的是Schema验证.
验证数据并向用户显示自定义错误消息的最佳做法是什么?
假设我们有这个简单的Schema:
var mongoose = require("mongoose");
// create instance of Schema
var Schema = mongoose.Schema;
// create schema
var Schema = {
"email" : { type: String, unique: true },
"password" : String,
"created_at" : Date,
"updated_at" : Date
};
// Create model if it doesn't exist.
module.exports = mongoose.model('User', Schema);
Run Code Online (Sandbox Code Playgroud)
我想让注册用户拥有独特的电子邮件,所以我已添加unique: true到我的架构中.现在,如果我想向用户显示错误消息,说明为什么他没有注册,我会收到类似这样的回复:
"code": 11000,
"index": 0,
"errmsg": "E11000 duplicate key error index: my_db.users.$email_1 dup key: { : \"test@test.com\" }",
"op": {
"password": "xxx",
"email": "test@test.com",
"_id": …Run Code Online (Sandbox Code Playgroud) 我有以下架构。
var UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
test: {
type: String,
default: 'hello world'
}
});
UserSchema.pre('save', function(callback) {
var user = this;
this.test = undefined; // here unset test field which prevent to add in db
});
module.exports = mongoose.model('User', UserSchema);
Run Code Online (Sandbox Code Playgroud)
但是当我找到数据时
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
Run Code Online (Sandbox Code Playgroud)
它总是返回
[
{
_id: "56fa6c15a9383e7c0f2e4477",
username: "abca",
password: "$2a$05$GkssfHjoZnX8na/QMe79LOwutun1bv2o76gTQsIThnjOTW.sobD/2",
__v: 0,
test: "hello world" …Run Code Online (Sandbox Code Playgroud) 定义Mongoose模式时,通常应谨慎指定应存在哪些索引.也就是说,在许多情况下,我们希望控制创建的索引的名称,尤其是当这些索引是复合的,这样它们是可以理解的.
实际上,在创建某些索引时,需要明确指定索引名称以避免超出index name length limit.
由于ensureIndex(在默认情况下)对模式中定义的索引进行调用,因此控制由ensureIndex创建的索引名称的适当语法是什么?我认为使用字段级索引语法是不可能的,但它肯定可用于模式级索引吗?
var ExampleSchema = new Schema({
a: String,
b: String,
c: Date,
d: Number,
e: { type: [String], index: true } // Field level index
});
// We define compound indexes in the schema
ExampleSchema.index({a: 1, b: 1, c: 1});
ExampleSchema.index({d:1, e:1}, {unique: true});
Run Code Online (Sandbox Code Playgroud)
值得注意的是,db.collection.ensureIndex已弃用(通过mongodb),现在是别名db.collection.createIndex.
这是我的文件。
"calendar": {
"_id": "5cd26a886458720f7a66a3b8",
"hotel": "5cd02fe495be1a4f48150447",
"calendar": [
{
"_id": "5cd26a886458720f7a66a413",
"date": "1970-01-01T00:00:00.001Z",
"rooms": [
{
"_id": "5cd26a886458720f7a66a415",
"room": "5cd17d82ca56fe43e24ae5d3",
"price": 10,
"remaining": 8,
"reserved": 0
},
{
"_id": "5cd26a886458720f7a66a414",
"room": "5cd17db6ca56fe43e24ae5d4",
"price": 12,
"remaining": 8,
"reserved": 0
},
{
"_id": "5cd26a886458720f7a66a34",
"room": "5cd17db6ca45fe43e24ae5e7",
"price": 0,
"remaining": 0,
"reserved": 0
}
]
},
}
Run Code Online (Sandbox Code Playgroud)
这是我的shema:
const calendarSchema = mongoose.Schema({
hotel: {
type: mongoose.Schema.ObjectId,
ref: "Hotel",
required: true
},
city: {
type: mongoose.Schema.ObjectId,
ref: "City"
},
calendar: [
{
date: …Run Code Online (Sandbox Code Playgroud) 在这里,我尝试使用 userId 获取用户创建的地点。这是用户模型和地点模型,在控制器中,我编写了通过 userId 获取地点的逻辑。不幸的是,我在 res.json({}) 方法中发送响应时收到错误“UnhandledPromiseRejectionWarning: TypeError: place.toObject is not a function”。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const placeSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
image: { type: String, required: true },
address: { type: String, required: true },
location: {
lat: { type: Number, required: true },
lng: { type: Number, required: true },
},
creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User'} …Run Code Online (Sandbox Code Playgroud) 我在模型中有以下方法UserSchema:
userSchema.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() {
return this._password;
}
);
Run Code Online (Sandbox Code Playgroud)
但是当我创建 newteacher我有错误hashed_password is required。所以我认为virtualfrom 的userSchema方法不是继承于teacherSchema. 如何设置teacherSchema像virtualfrom这样的继承方法userSchema?
模型
const mongoose = require('mongoose');
extend = require('mongoose-extend-schema');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
trim: true,
required: true,
maxLength: 32
},
surname: {
type: String,
trim: true,
required: true, …Run Code Online (Sandbox Code Playgroud) mongoose-schema ×10
mongoose ×9
mongodb ×7
node.js ×6
database ×1
express ×1
javascript ×1
typescript ×1