mongoose - 'save'方法不存在

Mat*_*ian 3 mongoose mongodb node.js

考虑在MongooseJS上运行的mongodb集合.

示例代码:

Person.where('uid').equals(19524121).select('name').exec(function(err, data){
     // Here I can get the data correctly in an array.
     console.log(JSON.stringify(data)); 
     data[0].name = "try to save me now"; // Select the first item in the array
     data[0].save(); // Object #<Promise> has no method 'save'.
}
Run Code Online (Sandbox Code Playgroud)

错误 - 似乎找不到解决这个问题的方法.

对象#<Promise>没有方法'save';

我对为什么会发生这种情况感到有些困惑,我已经研究了很多,似乎无法找到直接的答案.

Aus*_*ins 12

a的结果find是一组记录.你可能想要循环这些记录,如下所示:

Person.find({ uid: /19524121/ }).select('name').exec(function(err, data){
  for(var i = 0; i < data.length; i++) {
     var myData = new Person(data[i]);
     myData.name = "try to save me now";
     myData.save(); // It works now!
  }
}
Run Code Online (Sandbox Code Playgroud)

此外,从猫鼬主页,看起来函数回调原型function(err, data),而不是相反,你在上面纠正.

从主页看这个:

var fluffy = new Kitten({ name: 'fluffy' });
Run Code Online (Sandbox Code Playgroud)

如果data[0]当前有一个常规的JSON对象,我们需要这样一行来转换为BSON模型对象.

var myData = new Person(data[0]);
Run Code Online (Sandbox Code Playgroud)