数字类型错误与猫鼬模型
Number TypeError with Mongoose Model?
500 内部服务器错误,Error: TypeError: path must be a string
浏览器控制台指向 ItemCtrl.js:35
console.log('Error: ' + data);
错误的堆栈跟踪如下所示:
类型错误:路径必须是字符串 at Query.where (/Users/Name/Downloads/dev/v16/node_modules/mongoose/lib/query.js:593:11) at Function.where (/Users/Name/Downloads/dev/v16/node_modules/mongoose/lib/model.js:1040:18) 在模型。(/用户/名称/下载/dev/v16/应用程序/模型/项目.js:44:35) ...
错误似乎来自/app/models/item中的一行.js特别是在else if
声明中。因为随着else if
被注释掉,if
和else
都有效。
// load mongoose since we need it to define a schema and model
var mongoose = require('mongoose');
var ItemSchema = mongoose.Schema({
title : String,
position: Number
});
// before validation starts, the number of Items is counted..afterwards, the position is set
ItemSchema.pre("validate", function(next) {
var doc = this;
// if 'position' is not filled in, fill it in
// not using !position because 0 might be a valid value
if(typeof doc.position !== "number") {
// count the number of Items *
// use mongoose.model to fetch the model because it is not compiled yet
mongoose.model("Item").count(function(err, num) {
// if there was an error, pass it to next()
if(err)
return next(err);
// set the position, then call next();
doc.position = num;
return next();
});
} else if(typeof doc.position == "number") {
console.log('yes, a number');
// check if there is an existing document with the same position
// use mongoose.model to fetch the model because the model is not compiled yet
mongoose.model("Item").where({_id: {$ne: doc._id}, position: doc.position}).count( function (err, count) {
// if there was an error, pass it to next()
if(err)
return next(err);
// if there is a doc with the SAME position, execute an update to MOVE DOWN all the $gte docs
if(count > 0) {
// use mongoose.model to fetch the model because the model is not compiled yet
mongoose.model("Item").update({position: {$gte: doc.position}}, {position: {$inc: 1}}, {multi: 1}, function(err, numAffected) {
console.log(numAffected);
// Call next() (with or without an error)
next(err);
});
} else {
// there are no docs that need to move down, so call next()
next();
}
});
} else {
// there is no need to count or update positions, so call next()
next();
}
});
module.exports = mongoose.model('Item', ItemSchema);
- 数据的路径是这样的:
- /public/views/CreateItem.html 中的表单域
- 到/public/js/controllers/ItemCtrl.js
- to/public/js/services/ItemService.js
- 到/app/routes.js
- 到/app/models/item.js
- 并且数据可以在本地主机:8080/API/Items 的 JSON 中查看
/public/views/CreateItem.html
<form>
<div class="form-group">
<!-- BIND THESE VALUES TO formData.value IN ANGULAR -->
<input type="text" class="form-control input-lg text-center" placeholder="Item" ng-model="formData.title">
<input type="number" class="form-control input-lg text-center" placeholder="0" ng-model="formData.position">
</div>
<!-- createItem() WILL CREATE THE NEW ITEM VIA ANGULAR THROUGH NODE API TO MONGOOSE -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createItem()">Add Item</button>
</form>
/public/js/controllers/ItemCtrl.js
angular.module('ItemCtrl', [])
// inject the Item service.factory into our controller
.controller('ItemController', function($scope, $http, Items, isEmptyObjectFilter) {
$scope.formData = {};
// CREATE ==================================================================
// when submitting the add form, send the text to the node API
$scope.createItem = function() {
// validate the formData (using our exentions.js .filter) to make sure that something is there..if form is empty, nothing will happen
if (!isEmptyObjectFilter($scope.formData)) {
// call the create function from our service (returns a promise object)
Items.create($scope.formData)
// if successful creation, call our get function to get all the new items
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.items = data; // assign our new list of items
})
.error(function(data) {
console.log('Error: ' + data);
});
}
};
});
/public/js/services/ItemService.js
angular.module('ItemService', [])
// super simple service
// each function returns a promise object
.factory('Items', function($http) {
return {
get : function() {
return $http.get('/api/items');
},
create : function(itemData) {
return $http.post('/api/items', itemData);
}
}
});
/app/routes.js
// load the item model
var Item = require('./models/item');
// expose the routes to our app with module.exports
module.exports = function(app) {
// create item and send back all items after creation
app.post('/api/items', function(req, res) {
console.log(req.body.position);
// create an item, information comes from AJAX request from Angular
Item.create({
title : req.body.title,
position : req.body.position
}, function(err, item) {
if (err)
res.send(err);
// get and return all the items after you create another
Item.find(function(err, items) {
if (err)
res.send(err)
res.json(items);
});
});
});
};
这里的问题是猫鼬 API 实际上并没有按照您尝试的方式使用where
。
Mongoose for Model.where 的 v3.8.8 文档显示,您可以以 ActiveRecord 样式的方式使用它,将属性名称(如 'age'
)与条件方法(如 gte
)链接以形成查询:
User.find({age: {$gte: 21}, callback)
相当于
User.where('age').gte(21).exec(callback)
您的代码使用 Model#find
的条件哈希样式,而不是 where
的链接方法样式。
这是应该重写的行:
mongoose.model("Item").where({_id: {$ne: doc._id}, position: doc.position}).count( function (err, count) {
最简单的方法是删除最后的.count
,然后将.where
更改为.count
,因为猫鼬的Model#count
像您在这里一样需要一系列条件。代码应如下所示:
mongoose.model("Item").count({_id: {$ne: doc._id}, position: doc.position}, function (err, count) {
如果要使用.where
语法,则需要像这样操作:
mongoose.model("Item").where('_id').ne(doc._id).where('position').equals(doc.position).count( function(err, count)
- FilterHeader不适用于模型字段类型对象
- 对“类型”和“状态”字段的更新会中断WSAPI中的模型检索
- POST to Django 模型与 ManyToManyFiled 给出不正确的类型.预期 pk 值,
- ng模型在角度1.3中输入类型数的投掷误差
- 获取成员数据模型中任何属性的属性类型
- angularJS + 猫鼬: 类型错误: 无法读取未定义的属性“模型”
- 一个集合中的不同模型类型 主干
- 如何在 Ember.js 中保存属性类型为“date”的模型
- AngularJS和输入类型=日期,如何格式化模型数据
- Backone 关系子模型类型
- AngularJS:根据模型类型显示适当的表单元素
- 类型错误:“未定义”不是构造函数 - 主干模型
- 续集模型中字段的数据类型
- 在Angular模型中,可以在JSON对象和字符串之间切换值类型吗
- 如何访问hasMany数组的模型类型
- Viewmodel属性'链接'找不到模型类型
- 在Backbone中使用Typescript定义一个collection's模型类型
- 在Ext JS存储中反序列化json数据时区分模型类型
- 使用Mongoose引用具有未知模型类型的对象
- 基于模型类型的成员组件