本文将带您了解关于javascript–Mongoose嵌入式文档更新的新内容,另外,我们还将为您提供关于javascript–Express/Mongoose应用程序的结构、javascript–L
本文将带您了解关于javascript – Mongoose嵌入式文档更新的新内容,另外,我们还将为您提供关于javascript – Express / Mongoose应用程序的结构、javascript – Lodash与mongoose合并、javascript – Model.find()在节点上的mongoose(mongodb)中返回null json对象、javascript – mongoDB / mongoose设计的关系数据库设计的实用信息。
本文目录一览:- javascript – Mongoose嵌入式文档更新
- javascript – Express / Mongoose应用程序的结构
- javascript – Lodash与mongoose合并
- javascript – Model.find()在节点上的mongoose(mongodb)中返回null json对象
- javascript – mongoDB / mongoose设计的关系数据库设计
javascript – Mongoose嵌入式文档更新
我定义的方案:
var Talk = new Schema({ title:{type: String,required: true},content: {type: String,date: { type: Date,comments: { type: [Comments],required: false},Vote: { type: [VoteOptions],}); var VoteOptions = new Schema({ option: {type: String,required: true },count: {type: Number,required: false } });
现在我想更新Vote.count,给定的Talk ID和VoteOption id.我有以下功能来完成这项工作:
function makeVote(req,res){ Talk.findOne(req.params.id,function(err,talk) { for (var i=0; i <talk.Vote.length; i++){ if (talk.Vote[i]._id == req.body.Vote){ talk.Vote[i].count++; } } talk.save(function(err){ if (err) { req.flash('error','Error: ' + err); res.send('false'); } else { res.send('true'); } }); }); }
一切执行,我得到res.send(‘true’),但是count的值不会改变.
当我做了一些console.log我看到它改变了价值,但talk.save不保存在db.
另外我很不高兴的循环只是找到_id的嵌入式文档.在mongoose文档中,我阅读了关于talk.Vote.id(my_id),但这给我没有id功能的错误.
解决方法
talk.markModified("Vote"); // mention that `talk.Vote` has been modified talk.save(function(err) { // ... });
希望这能帮助未来的人,因为我找不到答案很快.
Reference:
… Mongoose loses the ability to auto detect/save those changes. To “tell” Mongoose that the value of a Mixed type has changed,call the
.markModified(path)
method of the document passing the path to the Mixed type you just changed.
javascript – Express / Mongoose应用程序的结构
我应该如何构建我的express / mongoose应用程序,以便我可以使用我的模式,模型,路由以及在命中这些路由时调用的函数?
server.js
// setup
var express = require("express");
var app = express();
var mongoose = require("mongoose");
app.db = mongoose.connect( ''mydb'' ) );
// this is the bit I am not sure about
var UserSchema = require( ''./modules/users/schema'' )( app, mongoose );
var routes = require( ''./modules/users/routes'' )( app, mongoose, UserSchema );
// listen
app.listen( 3000 );
模块/用户/ schema.js
exports = module.exports = function( app, mongoose )
{
var UserSchema = mongoose.Schema(
{
username: { type: String, required: true },
password: { type: String }
});
var usermodel = mongoose.model( ''User'', UserSchema, ''users'' );
// it looks like this function cannot be accessed
exports.userlist = function( db )
{
return function( req, res )
{
usermodel.find().limit( 20 ).exec( function( err, users )
{
if( err ) return console.error( err );
res.send( users );
});
};
};
}
模块/用户/ routes.js
function setup( app, mongoose, UserSchema )
{
var db = mongoose.connection;
// get all users
app.get( ''/api/v1/users'', UserSchema.userlist( db) ); // this function cannot be accessed
// get one user
app.get( ''/api/v1/users/:id'', UserSchema.userone( db ) );
// add one new user
app.post( ''/api/v1/users'', UserSchema.addone( db ) );
}
// exports
module.exports = setup;
PS:我得到的错误是app.get(‘/ api / v1 / users’,UserSchema.userlist(db));
TypeError:无法调用undefined(routes.js)的方法’userlist’.
解决方法:
有或多或少的两个轴来组织您的代码.根据模块的层功能(数据库,模型,外部接口)或按功能/上下文(用户,订单)组织代码.大多数(MVC)应用程序使用功能组织架构,该架构更易于处理,但不会泄露应用程序的目的或意图.
除了组织代码之外,功能层应该尽可能地分离.
代码中的功能层是
>在应用程序中抽象数据和行为的模型
>构成应用程序外部接口的路由.路线不是应用程序!
>引导代码(server.js),负责启动和连接应用程序的各个部分
上面的代码库似乎使用了功能组织架构,这很好.使用模块目录对我来说并没有多大意义,似乎是多余的.所以我们有一个像这样的架构
|- server.js
|+ users
|- schema.js
|- routes.js
现在让我们打破一些依赖…
schema.js
代码的模式/模型部分不应该依赖于代表应用程序接口的应用程序.此版本的schema.js导出模型,不需要将快速应用程序或mongoose实例传递到某种工厂函数:
var mongoose = require(''mongoose'');
var Schema = mongoose.Schema;
var UserSchema = Schema({
username: { type: String, required: true },
password: { type: String }
});
// Use UserSchema.statics to define static functions
UserSchema.statics.userlist = function(cb) {
this.find().limit( 20 ).exec( function( err, users )
{
if( err ) return cb( err );
cb(null, users);
});
};
module.exports = mongoose.model( ''User'', UserSchema, ''users'' );
显然这会错过原始文件中的app.send功能.这将在routes.js文件中完成.您可能会注意到我们不再导出/ api / v1 / users而是/.这使快递应用程序更加灵活,路径自包含.
见this post for a article explaining express routers in detail.
var express = require(''express'');
var router = express.Router();
var users = require(''./schema'');
// get all users
router.get( ''/'', function(req, res, next) {
users.userlist(function(err, users) {
if (err) { return next(err); }
res.send(users);
});
});
// get one user
router.get( ''/:id'', ...);
// add one new user
router.post( ''/'', ...);
module.exports = router;
此代码省略了获取一个用户和创建新用户的实现,因为这些应该与用户列表非常相似.用户列表路由现在只负责在HTTP和您的模型之间进行调解.
最后一部分是server.js中的接线/引导代码:
// setup
var express = require("express");
var app = express();
var mongoose = require("mongoose");
mongoose.connect( ''mydb'' ); // Single connection instance does not need to be passed around!
// Mount the router under ''/api/v1/users''
app.use(''/api/v1/users'', require(''./users/routes''));
// listen
app.listen( 3000 );
因此,模型/模式代码不依赖于应用程序接口代码,接口具有明确的责任,server.js中的接线代码可以决定在哪个URL路径下安装哪个版本的路由.
总结
以上是小编为你收集整理的javascript – Express / Mongoose应用程序的结构全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
原文地址:https://codeday.me/bug/20190717/1491151.html
javascript – Lodash与mongoose合并
我正在尝试将现有的mongo实体与请求有效负载主体中的json对象合并.
exports.update = function(req,res) { if(req.body._id) { delete req.body._id; } Entity.findById(req.params.id,function (err,entity) { if (err) { return handleError(res,err); } if(!entity) { return res.send(404); } var updated = _.merge(entity,req.body); updated.save(function (err) { if (err) { return handleError(res,err); } return res.json(200,entity); }); }); };
遗憾的是,这不起作用.我收到了这个错误
node_modules/mongoose/lib/document.js:1272 doc.save(handleSave); ^ TypeError: Object #<Object> has no method 'save'
我已经尝试创建自己的自定义合并方法,但仍然无法实现正确的合并:
exports.update = function(req,err); } if(!entity) { return res.send(404); } var updated = merger(resume,req.body)//_.merge(resume,entity); }); }); }; function merger (a,b) { if (_.isObject(a)) { return _.merge({},a,b,merger); } else { return a; } };
有这种差异,我有这样的信息:
node_modules/mongoose/lib/document.js:1245 return self.getValue(i); ^ TypeError: Object #<Object> has no method 'getValue'
因此,我无法将实体的值和req.body扩展到更新的目标.我估计只有结构被复制了.有人请让我知道我哪里错了.谢谢.
解决方法
exports.update = function(req,err); } if(!entity) { return res.send(404); } _.extend(entity,req.body); entity.save(function (err) { if (err) { return handleError(res,entity); }); }); };
javascript – Model.find()在节点上的mongoose(mongodb)中返回null json对象
app.get('/all',function(req,res) { Party.find({},[],function(p) { console.log(p); }); res.redirect('/'); });
应该返回数据库中的所有集合 – 在控制台中返回null.
var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost/impromptu'); var Schema = mongoose.Schema,ObjectId = Schema.ObjectId;
初始化的一般事项
var PartySchema = new Schema({ what : String,when : String,where : String }); mongoose.model('Party',PartySchema); // Models var Party = db.model('Party');
模式
我有其他一切正确设置,我可以保存集合很好,由于某种原因无法检索所有…
检查了/var/log/mongodb.log,它确实是连接的.
有任何想法吗?
解决方法
Party.find({},function(err,p) { console.log(p); });
javascript – mongoDB / mongoose设计的关系数据库设计
**Users Table** user_id username email password **Games Table** game_id game_name **Lobbies Table** lobby_id game_id lobby_name **scores Table** user_id game_id score
因此,每个大厅属于一个游戏,多个大厅可以属于同一个游戏.用户对于不同的游戏也有不同的分数.到目前为止,对于我的用户架构,我有以下内容:
var UserSchema = new mongoose.Schema({ username: { type: String,index: true,required: true,unique: true },email: { type: String,required: true },password: { type: String,required: true } });
所以我的问题是,如何将关系设计结构化为mongoDB / mongoose模式?谢谢!
编辑1
我现在尝试创建所有模式,但我不知道这是否是正确的方法.
var UserSchema = new mongoose.Schema({ _id: Number,username: { type: String,scores: [{ type: Schema.Types.ObjectId,ref: 'score' }] }); var GameSchema = new mongoose.Schema({ _id: Number,name: String }); var LobbySchema = new mongoose.Schema({ _id: Number,_game: { type: Number,ref: 'Game' },name: String }); var scoreSchema = new mongoose.Schema({ _user : { type: Number,ref: 'User' },_game : { type: Number,score: Number });
解决方法
您在Edit 1中的方法基本上是正确的,但是您通常不希望基于Number填充远程ref或将模型的_id设置为Number,因为mongo使用它自己的散列机制来管理_id,这通常是隐含了_id的ObjectId.示例如下所示:
var scoreSchema = new mongoose.Schema({ user : { type: Schema.Types.ObjectId,game : { type: Schema.Types.ObjectId,score: Number });
如果由于某种原因你需要为你的记录保留一个数字id,可以考虑将其称为uid或者与mongo / mongoose内部不冲突的东西.祝好运!
关于javascript – Mongoose嵌入式文档更新的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于javascript – Express / Mongoose应用程序的结构、javascript – Lodash与mongoose合并、javascript – Model.find()在节点上的mongoose(mongodb)中返回null json对象、javascript – mongoDB / mongoose设计的关系数据库设计等相关内容,可以在本站寻找。
本文标签: