我正在使用Hapi开发一个Web服务,Mongoose作为ODM,Joi作为验证器.我真的很喜欢Joi的验证以及它与HAPI连接的方式(我需要Joi的描述函数来显示一些swagger的描述)但是我不想维护两个模式,一个用于Joi,一个用于mongoose; 我想使用Joi定义我的模式,然后只能导出Mongoose所需的基本模式.例如:
mySchema.js
module.exports = {
name : String,
address: String
}
Run Code Online (Sandbox Code Playgroud)
myValidator.js
module.exports = {
payload: {
name: Joi.description('A name').string().required(),
address: Joi.description('An address').string()
}
}
Run Code Online (Sandbox Code Playgroud)
myModel.js
const mongoose = require('mongoose'),
mySchema = require('./mySchema');
var schemaInstance = new mongoose.Schema(mySchema),
myModel = mongoose.model('myModel', schemaInstance);
Run Code Online (Sandbox Code Playgroud)
myHapiRoute.js
const myValidator = require('./myValidator.js'),
myController = require('./myController.js');
...
{
method: 'POST',
path: '/create',
config: {
description: 'create something',
tags: ['api'],
handler: myController,
validate: myValidator
}
}
...
Run Code Online (Sandbox Code Playgroud)
我想避免麻烦,保持mySchema.js文件生成它究竟来自淳佳的架构.
有关如何做或任何不同方法的任何建议?
我想开始利用Mongooses文档版本控制(__v key).我有一个实际增加版本值的问题,然后我发现你必须this.increment()在执行查询时添加.
有没有办法自动递增?目前,我刚刚将它添加到预中间件以获取更新类型的查询:
module.exports = Mongoose => {
const Schema = Mongoose.Schema
const modelSchema = new Schema( {
name: Schema.Types.String,
description: Schema.Types.String
} )
// Any middleware that needs to be fired off for any/all update-type queries
_.forEach( [ 'save', 'update', 'findOneAndUpdate' ], query => {
// Increment the Mongoose (__v)ersion for any updates
modelSchema.pre( query, function( next ) {
this.increment()
next()
} )
} )
}
Run Code Online (Sandbox Code Playgroud)
这似乎有用..但我有点认为在Mongoose中已经有办法做到这一点..我错了吗?
我在Mongoose> = 4.4中找不到任何涉及自定义对象(或值对象)的高级 自定义模式类型的示例.
想象一下,我想使用自定义类型,如:
function Polygon(c) {
this.bounds = [ /* some data */ ];
this.npoints = /* ... */
/* ... initialize polygon ... */
};
Polygon.prototype.area = function surfaceArea() { /**/ };
Polygon.prototype.toObject = function toObject() { return this.bounds; };
Run Code Online (Sandbox Code Playgroud)
接下来,我实现了一个自定义SchemaType,如:
function PolygonType(key, options) {
mongoose.SchemaType.call(this, key, options, 'PolygonType');
}
PolygonType.prototype = Object.create(mongoose.SchemaType.prototype);
PolygonType.prototype.cast = function(val) {
if (!val) return null;
if (val instanceof Polygon) return val;
return new Polygon(val)
}
PolygonType.prototype.default = …Run Code Online (Sandbox Code Playgroud) 使用以下架构:
{
data1: String,
nested: {
nestedProp1: String,
nestedSub: [String]
}
}
Run Code Online (Sandbox Code Playgroud)
当我这样做时,new MyModel({data1: 'something}).toObject()显示新创建的文档:
{
'_id' : 'xxxxx',
'data1': 'something',
'nested': {
'nestedSub': []
}
}
Run Code Online (Sandbox Code Playgroud)
即使用空数组创建嵌套文档.
如何使"嵌套"完全可选 - 即如果未在输入数据上提供,则根本不创建?
我不想为"嵌套" 使用单独的模式,不需要那种复杂性.
我正在尝试更新架构以添加新的属性字段.我希望它可以像将属性添加到模式一样简单,并且可以访问更新的字段.
我有一个现有的架构
let userDrinkSchema = new mongoose.Schema({ new Schema
creator : {
type: mongoose.Schema.Types.ObjectId,
ref: 'user' // name of user file
},
caffeine: Number,
mgFloz: Number,
name: String,
size: Number,
updated_at: {
type: Date,
default: Date.now()
}
});
Run Code Online (Sandbox Code Playgroud)
我需要从这个架构中添加id
const UserSchema = mongoose.Schema({
const User = module.exports = mongoose.model('User', UserSchema);
Run Code Online (Sandbox Code Playgroud)
我不知道如何为每个用户添加此属性.我按照这个例子 处理了Mongoose中的模式更改
架构现在是:
let DrinkSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
required: true,
default: null
},
caffeine: Number,
mgFloz: Number,
name: String,
size: Number,
imageUrl: String,
date: …Run Code Online (Sandbox Code Playgroud) 尝试更新MongoDB文档获取弃用警告为
(节点:71307)[DEP0079]弃用警告:不推荐使用.inspect()对象的自定义检查功能
节点版本v10.5.0,db版本v3.6.5,Mongoose版本mongoose@4.1.12
Campground.findById(campgroundId, function(err, campground){
if(err){
console.log(err);
} else {
console.log(campground.celebrity);
Celebrity.create(celebrityData, function(err, celebrity){
if(err){
console.log(err);
} else {
//save comment
celebrity.save();
campground.celebrity.push(celebrity);
campground.save();
console.log(celebrity);
//req.flash('success', 'Created a comment!');
}
});
}
});
Run Code Online (Sandbox Code Playgroud) 想象一下,我有以下型号:
# MODEL A
schemaA = mongoose.Schema
_bId:
type: mongoose.Schema.Types.ObjectId
ref: "B"
# MODEL B
schemaB = mongoose.Schema
_cId:
type: mongoose.Schema.Types.ObjectId
ref: "C"
_dId:
type: mongoose.Schema.Types.ObjectId
ref: "D"
# MODEL C
schemaC = mongoose.Schema
_eId:
type: mongoose.Schema.Types.ObjectId
ref: "E"
Run Code Online (Sandbox Code Playgroud)
模型D和E没有任何其他对象引用,因此不再列出为方便起见.
使用所有引用填充模型"A"的最佳实践是什么?目前我按如下方式解决此任务(它是一个实例方法,因为我经常需要它):
schemaA.methods =
populateAll: (cb) ->
@
.populate
path: "_bId"
model: "B"
populate:
path: "_cId"
model: "C"
populate:
path: "_eId"
model: "E"
, (error) =>
return cb error, @ if error?
D.findById @._bId._dId
.exec (error, d) =>
return cb error, …Run Code Online (Sandbox Code Playgroud) 我有一个模型,在第一次POST后不断出错.我正在创建一个X天的调度应用程序,包括房间和房间的时间段.
我遇到的问题是在数据库中创建Day Objects.为了便于阅读,我将只有一个键值对
day.model.js
var mongoose = require('mongoose');
// Day Schema
var daySchema = mongoose.Schema({
name:{
type: String,
required: true,
},
createdAt:{
type: Date,
default: Date.now
}
});
var Day = module.exports = mongoose.model('Day', daySchema);
// Get all Days
module.exports.getDays = function(callback, limit){
Day.find(callback).limit();
};
// Add Day
module.exports.addDay = function(day, callback){
var add = {
name: day.name,
};
Day.create(add, callback);
};
Run Code Online (Sandbox Code Playgroud)
day.routes.js
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var config = require('../config/database');
Day …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Mongoose和MongoDB向父模式添加子文档但是我被抛出以下错误:
TypeError: User is not a constructor
Run Code Online (Sandbox Code Playgroud)
这是基于Mongoose关于子文档的文档,我认为一切都是一样的.我该如何进一步调试?
路由器
// Add a destination to the DB
router.post('/add', function(req, res, next) {
let airport = req.body.destination
let month = req.body.month
let id = (req.user.id)
User.findById(id , function (err, User) {
if (err) return handleError(err)
function addToCart (airport, month, id) {
var user = new User ({
destinations: [(
airport = '',
month = ''
)]
})
dog.destinations[0].airport = airport
dog.destinations[0].month = month
dog.save(callback)
res.status(200).send('added')
}
addToCart()
})
console.log(airport)
}) …Run Code Online (Sandbox Code Playgroud) 我有一个情况,我正在检查文档是否已存在,如果不存在,我将创建一个新文档。我需要填充文档内的 2 个字段。我的问题是.create方法不支持.populate方法,因为如果我尝试这样做,我会收到错误。此外,. populate方法也不适用于返回的文档。如何正确填充新创建的文档?这是我的代码:
Favorite.create({ user: req.user._id, dishes: req.params.dishId })
.then((favorite) => {
favorite.populate('user');
favorite.populate('dishes');
console.log('Favorite marked', favorite);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(favorite);
}, (err) => next(err))
}
})
.catch((err) => next(err));
Run Code Online (Sandbox Code Playgroud) mongoose-schema ×10
mongoose ×9
mongodb ×7
node.js ×7
express ×2
javascript ×2
hapijs ×1
joi ×1
promise ×1