使用Jasmine-Node进行testing时,Mongoose模型自定义函数中消失的值

我试图在我的Mongoose模型上testing我的自定义方法,但是我在testing模型中设置的值消失,并使testing失败。 testing看起来像这样:

it('should get the friend id', function(){ var conversation = new Conversation({ 'users': [new ObjectId('0'), new ObjectId('1')] }); expect(conversation.getFriendId('0')).toEqual(new ObjectId('1')); }); 

我的模型声明包含这个:

 var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; var ConversationSchema = new mongoose.Schema({ 'users': [{'type': ObjectId, 'ref': 'User'}] }); ConversationSchema.methods.getFriendId = function(userId) { return this.users; //return this.users[0] === new ObjectId(userId) // ? this.users[1] : this.users[0]; }; module.exports = mongoose.model('Conversation', ConversationSchema); 

当我运行testing时,我得到:

 Expected [ ] to equal { path : '1', instance : 'ObjectID', validators : [ ], setters : [ ], getters : [ ], options : undefined, _index : null }. 

我在testing中设置了用户,所以返回值应该是用户数组。 (在当前状态下,testing仍然失败,但在取消注释第二个返回语句时理论上应该通过),而users数组显示为空。

如何从testing模型中获取值以显示在我的自定义函数中?

我改变了一些东西,最终得到这个工作。

我将用户数组更改为一个类似于对象的对象,因为它是对数据更精确的表示。 该组的键是ObjectId的string。

要创build一个新的ObjectId,你必须有一个12字节的string或一个24字符的hexstring。 最初,我试图用一个单一的数字string。 我添加了一个spec助手,用24个字符的hexstring存储伪ID。

mongoose.Schema.Types.ObjectIdmongoose.Types.ObjectId是两个不同的东西。 我在尝试每一个之前意识到我需要使用两个。 在创buildSchema时,我需要mongoose.Schema.Types.ObjectId 。 任何其他时间我指的是ObjectIdtypes,我需要mongoose.Types.ObjectId

我试图从我定义他们访问它们的文件中返回模型。 相反,我需要调用mongoose.model()来获取我的模型。

通过这些更改,我的模型定义如下所示:

 var mongoose = require('mongoose'); var ObjectId = mongoose.Schema.Types.ObjectId; var ConversationSchema = new mongoose.Schema({ 'users': Object, 'messages': [ { 'text': String, 'sender': {'type': ObjectId, 'ref': 'User'} } ] }); ConversationSchema.methods.getFriendId = function(userId) { for (var u in this.users) { if (u !== userId) return new mongoose.Types.ObjectId(u); } return null; }; // other custom methods... mongoose.model('Conversation', ConversationSchema); 

我的testing看起来像这样:

 describe('getFriendId()', function(){ var mongoose = require('mongoose'); var ObjectId = mongoose.Types.ObjectId; require('../../../models/Conversation'); var Conversation = mongoose.model('Conversation'); var helper = require('../spec-helper'); it('should get the friend id', function(){ users = {}; users[helper.ids.user0] = true; users[helper.ids.user1] = true; var conversation = new Conversation({ 'users': users }); expect(conversation.getFriendId(helper.ids.user0)).toEqual(new ObjectId(helper.ids.user1)); }); });