Tag: 独特

尝试使用唯一索引保存mongoose文档时,节点服务器崩溃

我有一个集合,其中有一个领域作为一个独特的领域。 var ProductSchema = new mongoose.Schema({ code: {type:String, required:true}, name: {type:String, default:""} }); ProductSchema.index({ code: 1}, { unique: true }); 当我用一个已经存在的代码创build一个新文档时,服务器崩溃而不是通过callback返回一个错误: module.exports.create = function (params, callback){ var product = new ProductModel(params); product.save(function(error){ console.log(error); callback(error); }); } 这(崩溃)预期的行为或mongoose应通过callback返回一个错误,而不是崩溃? 这是我用相同的代码保存第二个文档时得到的错误: [..path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:245 throw message; ^ TypeError: Cannot read property '0' of undefined at […path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js:114:55 at […path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1132:7 at […path]/server/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1846:9 […]

mongoose:在任何组合的一对字段上的唯一索引

唯一性在多个字段可能通常意味着您不能具有某些字段的组合相同的文档,如name1和name2 。 所以它将不允许存在两个文件{name1: 'Joe', name2: 'Bob'} 。 如果name1和name2切换,例如{name1: 'Bob', name2: 'Joe'}和{name1: 'Joe', name2: 'Bob'}这仍然允许文档同时存在。 有没有办法让一个独特的索引不允许这两个? (如果{name1: 'Bob', name2: 'Joe'}存在,既不可以{name1: 'Bob', name2: 'Joe'}也不可以{name1: 'Joe', name2: 'Bob'} )

mongoose – 从每个用户find最后一条消息

我正在处理消息系统,我需要从发送消息给login用户的每个用户获取最后一条消息。 我在mongoDB中有这样的结构: [{ "_id": "551bd621bb5895e4109bc3ce", "from": "admin", "to": "user1", "message": "message1", "created": "2015-04-01T11:27:29.671Z" }, { "_id": "551bd9acf26208ac1d9b831d", "from": "user1", "to": "admin", "message": "message2", "created": "2015-04-01T11:42:36.936Z" }, { "_id": "551bdd6d849d53001dd8a64a", "from": "user1", "to": "user2", "message": "message3", "created": "2015-04-01T11:58:37.858Z" }, { "_id": "551bdd99849d53001dd8a64b", "from": "user2", "to": "admin", "__v": 0, "message": "message4", "created": "2015-04-01T11:59:21.005Z" }, { "_id": "551bdda1849d53001dd8a64c", […]