Tag: mongoose

MongoDB / mongoose在两个模型之间build立关系?

我正在寻找创build一个一对多的关系遵循这种模式http://docs.mongodb.org/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/ 我有一个Exercise.js模式,它将包含一系列练习。 var exerciseSchema = new mongoose.Schema({ _id: String, title: String, description: String, video: String, sets: Number, reps: String, rest: Number }); 然后我有一个锻炼计划BeginnerWorkout.js架构 var workoutDaySchema = new mongoose.Schema({ _id: String, day: Number, type: String, exercises: Array }); 我想将一系列练习与workoutDaySchema相关联,这包含特定锻炼的训练日的集合,每天都有一系列练习。 我有一个播种function,为我生成锻炼。 check: function() { // builds exercises Exercise.find({}, function(err, exercises) { if(exercises.length === 0) { console.log('there are […]

Mongoose $ push的问题

我真的只需要在这里第二套眼睛。 我正在使用Mongoose npm在MongoDB中创build一个新条目。 然后我在Async npm的几个函数中使用这个新的入口。 我遇到的问题是,我得到的前三个控制台日志,“击球手”,“创build”,“req.body.campaign_id”,但没有任何过去。 我认为它必须在我的第一个findByIdAndUpdate $推。 请参阅下面的代码和架构。 码! 请参阅asynchronous并行“活动”function Bid.create(req.body, function(err, bid){ console.log('create') async.parallel({ campaign: function(done) { console.log(req.body.campaign_id) Camapaign.findByIdAndUpdate(req.body.campaign_id, { $push: { bids: bid._id } }, { safe: true, upsert: true }, function(err, campaign){ console.log('camp', 2) if(err) { console.log(err) done(err) } else { done(null, campaign) } }); }, user: function(done) { console.log('user', 1) […]

与mongoose.createConnection一起使用node-restful

两个约束:使用node-restful和创build非全局连接(由于testing目的)使用mongoose.createConnection 下面的代码将不起作用: var someSchema = require('./someSchema'); var restful = require('node-restful'); var model = restful.model('some', someSchema); //far far away… var connection = restful.mongoose.createConnection(); connection.on('connected', function() { restful.register(app, '/somes'); } GET /somes导致无限循环某处或不触发callback。 无论如何, 节点restful model.js代码显示不支持连接和模型不知道任何关于当前连接。 有人知道如何提供连接模型? 我被困住了。

在模板中循环,在用玉进行编译时,“无法读取属性长度”的“未定义”错误

所以这是get route / users / search的searchfunction: // peopleRoutes.js:25:16 exports.search = function (req, res) { var term = req.query.term; User.find({$or: [ {username: {$in: [term]}}, {bio: {$in: [term]}}, {location: {$in: [term]}} ]}, function (err, users) { var fn = jade.compileFile('path/to/template.jade'), {}); var html = fn(users); res.setHeader("Content-Type", 'text/html'); res.send(html); res.end(); }).sort({username: 'asc'}); }; 这是我想要检索的模板: ul.list-group(id='main-list') for user in […]

Socket.io不保存在Mongoose上save()

我创build一个简单的聊天只是为了学习socket.io以及如何在MongoDb上保存MongoDb的数据。 经过一番研究,我仍然阻塞,因为mongoose不保存数据。 在这里我的configuration: // configuration var app = require('express')(); http = require('http').Server(app), io = require('socket.io')(http), mongoose = require('mongoose'); // connect to db mongoose.connect('mongodb://localhost/chat', function(err){ if(err){ console.log(err); }else{ console.log('Connected to MongoDb!'); } }); // Schema model var chatSchema = mongoose.Schema({ msg: String, created: {type: Date, default: Date.now} }, { collection: 'chat' }); // model var Chat […]

是否需要在父文档中持有对子代的引用 – Mongoose

在下面的例子中,我想检索填充相应注释的文档。 我是否需要将引用中的评论作为数组保存? 参照意见进行sorting意味着,每当更新新文档时,文档都会定期更新。 var Post = new schema({ content:String, author:{ type: Schema.ObjectId, ref: 'User' }, createdOn:Date }); var Comment = new Schema({ post : { type: Schema.ObjectId, ref: 'Post' }, commentText : String, author: { type: Schema.ObjectId, ref: 'User' }, createdOn:Date }); mongoose.model('Post',Post); mongoose.model('Comment',Comment); 如果我在Post中将Comment._Id引用为数组,那么在mongoose中,我可以像下面那样填充。 Post.findById(postid).populate('Comments').exec( callback); 但是,我不想在创build新评论时更新发布文档,因为您需要将评论ID推送到发布文档中。 评论有引用它所属的post,所以从技术上讲,可以retirve属于一个特定的职位的意见,但如果你想检索或发送单个json文件有可能没有数组包含引用文章中的评论?

Mongoose:如何将字段/值插入到现有的子文档中

我无法理解如何将新field:value objects添加到mongo数据库。 说我有以下document : var people={'firstname': 'John','surname':'Smith', 'favouritefood':[{'fruit':'apples','drink':'coffee'}]} 如何添加“蔬菜”:“西兰花”,以“最喜爱的食物”,所以它看起来像这样: {'firstname': 'John','surname':'Smith', 'favouritefood':[{'fruit':'apples','drink':'coffee','vegetable':'broccoli'}]} 如果我input: people.findOneAndUpdate({'firstname':'John'}, {$push {favouritefood: {vegetable:broccoli}}}, {upsert:true}) 它给了我这个: {'firstname': 'John','surname':'Smith', 'favouritefood':[{'fruit':'apples','drink':'coffee'},{'vegetable':'broccoli'}]} 如果我尝试: people.findOneAndUpdate({'favoritefood':'apples'}, {$push {vegetable:broccoli}}}, {upsert:true}) 它说: '$push' is empty. You must specify a field like so: {$push: {<field>: …}} 任何帮助是极大的赞赏!

如何读取json文件并将条目保存到mongodb

我parsing的是一个对象数组的JSON文件。 我想用一些逻辑来parsing这个数组,然后通过mongoose把每个条目保存到MongoDB中。 var fs = require('fs'); var Promise = require("bluebird"); var Show = require('../server/models/show'); Promise.promisifyAll(fs); // read file fs.readFileAsync('upcoming-shows.json', 'utf8') .then(function (resolve, reject) { var shows = JSON.parse(resolve); shows.forEach(function(show){ // first entries have no date if(typeof show.date != 'undefined'){ var formatDate = show.date.split('\n')[1].trim(); // Thu 08 Oct 2015 show.date = formatDate; var newShow = new […]

mongoose(mongodb)奇怪的行为时,没有参数查询

我正在使用邮递员张贴到我的后端得到一个基于他的用户名和密码的用户。 每当用户名在表单中不存在时,用户仍然返回(我现在只有一个用户,并且返回)。 但是,如果我添加用户名字段,它将返回null,除非它是正确的用户名,即使它是空的。 这是代码: User.findOne({ username: req.body.username }, function(err, user) { if(err) throw err; // prints null if username field is present and incorrect even if its empty // prints a user as json if the username field is not present console.log(user); if(!user) { res.json({ success: false, message: 'Authentication failed. User not found.' }); } […]

当在mongoose中find一些标准时获得空数组

架构: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Config = require('../Config'); var serviceAvailability = new Schema({ agentId: {type: Schema.ObjectId, ref: 'agentProfile', required: true}, availabilityDate: {type: Date, required: true}, availabilityTime: {type: Array, required: true} }); serviceAvailability.index({agentId:1 , availabilityDate:1},{unique:true}); module.exports = mongoose.model('serviceAvailability', serviceAvailability); 控制器: Models.serviceAvailability.find({'agentId':'abcd'}, function (err, service) { console.log(service); if(service) { callback(err , service); […]