javascript - Mongoose 模型的数字类型错误?

标签 javascript node.js angularjs mongodb mongoose

有一个 500 内部服务器错误,对于 错误:TypeError:路径必须是一个字符串

浏览器控制台指向ItemCtrl.js:35

console.log('Error: ' + data);

错误的堆栈跟踪如下所示:

TypeError: path must be a string 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) at model. (/Users/Name/Downloads/dev/v16/app/models/item.js:44:35) ...

似乎错误源自 /app/models/item.js 中的一行 特别是在 else if 语句中。 因为 else if 被注释掉了,ifelse 都可以工作..

// 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);
  • The path of the data is this:
  • form field in /public/views/CreateItem.html
  • to /public/js/controllers/ItemCtrl.js
  • to /public/js/services/ItemService.js
  • to /app/routes.js
  • to /app/models/item.js
  • and the data can be viewed in json at localhost:8080/api/items

/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);
            });
        });

    });
};

最佳答案

这里的问题是 mongoose API 实际上并没有像您尝试的那样使用 where

mongoose v3.8.8 的文档 Model.where显示您可以以 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( 函数 (err, count) {

最简单的做法是删除末尾的 .count 并将 .where 更改为 .count,因为 mongoose 的 Model#count 像您在这里一样采用条件散列。代码应该像这样工作:

mongoose.model("Item").count({_id: {$ne: doc._id}, position: doc.position}, 函数 (err, count) {

如果你想使用 .where 语法,你需要这样做:

mongoose.model("Item").where('_id').ne(doc._id).where('position').equals(doc.position).count( function(err, count )

关于javascript - Mongoose 模型的数字类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22919563/

相关文章:

javascript - 选择并复制输入文本onclick?

node.js - 异步编程中的循环

node.js - Jenkins 和 NodeJS

javascript - 带有查询参数的 AngularJS 身份验证问题?

javascript - 将按钮设置为 'active' 在 AngularJS 中不起作用

javascript - PHP 保存并重新获取复选框值

javascript - jQuery data() 和 attr() 方法,以及 JavaScript 数据集属性返回 undefined

ASP.NET MVC + Web API2 + AngularJS授权和身份验证

javascript - 为什么下面的函数会在控制台中记录 undefined ?它不应该抛出像未定义这样的错误吗?

node.js - Mongoose 查询嵌入文档