未定义的Nodejs Mongoose Saving模型不是函数 [英] Nodejs Mongoose Saving model undefined is not a function

查看:92
本文介绍了未定义的Nodejs Mongoose Saving模型不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Nodejs Express路由和Mongoose来保留数据. 我做核心路由CRUD操作没有问题.但是,当我尝试在Model的一个字段上执行一些操作,然后尝试将模型保存为model.save时,它会说.save()方法:未定义不是函数"

I work with Nodejs Express routes and Mongoose to persist data. I did the core routes CRUD operations with no problem. However, when I try to perform some operations on one of the fields of the Model and then try to save the Model with model.save it says about .save() method: "undefined is not a function"

所以,这是代码. 代码段编号(1)可以正常工作:

So, here's the code. The snippet number (1) works just fine:

router.put('/:myId', function (req, res, next) {
var ourUpdateData = req.body;
Model.findOne({myId: req.params.myId.toString()}, function (err, foundModel) {
    if (err) throw err;

    if (ourUpdateData.fieldA) foundModel.fieldA = ourUpdateData.fieldA;
    if (ourUpdateData.fieldB) foundModel.fieldB = ourUpdateData.fieldB;
    if (ourUpdateData.fieldC) foundModel.fieldC = ourUpdateData.fieldC;
    if (ourUpdateData.fieldD) foundModel.fieldD = ourUpdateData.fieldD;
    if (typeof ourUpdateData.fieldArray === "object") ourUpdateData.fieldArray = ourUpdateData.fieldArray;

    foundModel.save(function (err, updatedModel) {
        if (err) throw err;
        res.send(updatedmodel);
    });
});

});

因此,模型具有6个字段:fieldA,.. B,.. C,.. D,myId以标识为索引,并且一个字段是某些值的Array.上面的示例保存了Model,可以正常工作. 但是,如果我现在尝试对数组字段fieldArray做一些操作,然后保存模型,则在使用model.save()时会抛出未定义不是函数"的信息. 因此,代码段(2)是产生此错误的代码:

So the Model has 6 fields: fieldA,..B,..C,..D, myId to identify as index and one field is Array of some values fieldArray. The example above saves the Model, works fine. However if I now try to do something with array field fieldArray and then save the Model it throws me "undefined is not a function" when I use model.save() . So the snippet (2) is the code that produces this error:

    router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
    var myId = req.params.myId;
    var addThisToFieldArray = req.params.addThisToFieldArray;
    Model.find({myId: myId}, function (err, model) {
        if (err) throw err;
        var fieldArray = model.fieldArray;
        fieldArray.push("New thing to FieldArray");
        var newFieldArray = fieldArray;
        if (typeof newFieldArray === "object") model.fieldArray = newFieldArray;
        model.save(function (err, updatedModel){
            if (err) throw err;
            res.send(updatedModel);
        });
    });
});

因此,在使用model.save(..)时,上面的事情会抛出未定义的不是函数"

So that thing above throws "undefined is not a function" on using model.save(.. )

我还尝试了代码段(2)的第二种变体,我们称其为代码段(3),其中包含.exec()也不起作用,在model.save( ..) 因此,代码段(3)是这样的:

I also tried second variant of the snippet (2), let's call it snippet (3), incorporating the .exec() Also doesn't work, throws the same "undefined is not a function" on model.save(.. ) So the snippet (3) is this:

    router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
    var myId = req.params.myId;
    var addThisToFieldArray = req.params.addThisToFieldArray;
    Model.find({myId: myId}).exec(function (err, model) {
        if (err) throw err;
        var fieldArray = model.fieldArray;
        fieldArray.push("New thing to FieldArray");
        var newFieldArray = fieldArray;
        if (typeof newFieldArray === "object") model.fieldArray = newFieldArray;
        model.save(function (err, updatedModel){
            if (err) throw err;
            res.send(updatedModel);
        });
    });
});

我将非常感谢您提供任何意见和建议!

I'll be greatful for any inputs and suggestions!

为威尔森的尝试做准备:

Ansering to the attempt of Willson:

是的,我知道当我调用model.find(..它会提供数组,如果我调用model.findOne(..它会提供一个对象json

Yeah, I know when I call model.find(.. it gives array, if I call model.findOne(.. it gives one object json

我试图简化我的示例,在我的版本中,我确实使用了: "model [0] .fieldArray = newFieldArray"从Array fist(数组本身)中获取内容,然后分配给新值.

I tried to simplify my example and in my version I actualy did use the: "model[0].fieldArray = newFieldArray" to get the thing from Array fist (the array itself) and then assign to the new value.

问题仍然存在,它在model.save(.."undefined is not a function")上给我

The problem still persists, it gives me on model.save(.. "undefined is not a function " )

当前代码为:

    router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
    var myId = req.params.myId;
    var addThisToFieldArray = req.params.addThisToFieldArray;
    Model.find({myId: myId}).exec(function (err, model) {
        if (err) throw err;
        var fieldArray = model[0].fieldArray;
        fieldArray.push("New thing to FieldArray");
        var newFieldArray = fieldArray;
        if (typeof newFieldArray === "object") model[0].fieldArray = newFieldArray;
        model.save(function (err, updatedModel){
            if (err) throw err;
            res.send(updatedModel);
        });
    });
});

上面的代码段(4)给出了model.save(..未定义不是函数"

This snippet (4) above gives on model.save(.. "undefined is not a function"

推荐答案

在Mongoose中使用find方法时,它将返回一个数组,因为它可以发现一个或多个文档,因此在您的示例中,您要查询一个具有其ID的特定元素,您应该获取返回数组中的第一个元素:

When you use in Mongoose the find method, it will return an array since it could discover one or many documents, so in your example you are querying to one specific element by its id, you should grab the first element on the returned array:


     Model.find({myId: myId}).exec(function (err, documents) {
            var model = documents[0];

            if (err) throw err;
            var fieldArray = model[0].fieldArray;


这里是一个例子:


Here is an example:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost:27017/java-jedi');

var HackerSchema = new Schema({
  name: String,
  languages: [String]
});

var Hacker = mongoose.model('Hacker', HackerSchema);


// instantiating the model.
var oneHacker = new Hacker();
oneHacker.name = 'Richard Stallman';

oneHacker.save(function(err) {
  if (err) throw err;

  // finding the document intentionally for this example
  Hacker.find({_id: oneHacker._id}, function(err, hackers) {
    var hacker = hackers[0];

    // modifying the document and updating it.
    hacker.languages.push('Lisp');
    hacker.save(function(err) {
      if (err) throw err;

      console.log(hacker);
    });
  });

});

这篇关于未定义的Nodejs Mongoose Saving模型不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆