无法读取undefined属性'push'

时间:2017-04-19 10:53:58

标签: javascript node.js mongodb express mongoose

这是我的猫鼬模式:

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

var CartSchema = new Schema({
 userID: String,
 items: [{
   itemID: String,
   quantity: Number
 }]
});

module.exports = mongoose.model('Cart', CartSchema);

这是使用Express的node.js服务器。它有/add-to-cart路由,如果触发,它应该使用req.body中传递的信息更新用户的购物车:

router.post('/add-to-cart', function(req, res, next) {
      Cart.find({ userID: req.body.userID }).then(function(userCart){
          console.log("TEST: "+JSON.stringify(userCart));
          var myItem = {itemID: req.body.itemId, quantity: 1}
          userCart.items.push(myItem);
          res.send(userCart);
       }).catch(next);
    });

我打印到终端userCart,你可以在我的代码中看到,它返回给我:

[{
  "_id":"58f7368b42987d4a46314421",  // cart id
  "userID":"58f7368a42987d4a46314420", // userid
  "__v":0,
  "items":[]   
}]

当服务器执行userCart.items.push(myItem);时,它会返回以下错误:

Cannot read property 'push' of undefined

如果我已经在mongoose中定义了它的结构,为什么没有定义items

3 个答案:

答案 0 :(得分:0)

正确地adeneo pointed outFriend Function listTask() As DataTable Dim dtTasks As New DataTable dtTasks.Columns.Add("NAME") dtTasks.Columns.Add("STATE") dtTasks.Columns.Add("ARGS") Dim service service = CreateObject("Schedule.Service") Call service.Connect() ' Get the task folder that contains the tasks. Dim rootFolder rootFolder = service.GetFolder("\") Dim taskCollection 'As Microsoft.Win32.TaskScheduler.TaskCollection taskCollection = rootFolder.GetTasks(0) Dim numberOfTasks As Integer numberOfTasks = taskCollection.Count If numberOfTasks = 0 Then MsgBox("Não Existem Tarefas") Else Dim count As Integer = 0 Dim registeredTask For Each registeredTask In taskCollection 'For i = 0 To numberOfTasks - 1 Dim taskState As String Select Case registeredTask.State Case "0" taskState = "Unknown" Case "1" taskState = "Disabled" Case "2" taskState = "Queued" Case "3" taskState = "Ready" Case "4" taskState = "Running" End Select 'TENHO AQUI TUDO !!!!! Dim aaaa As String = registeredTask.xml Dim BodyDoc As XmlDocument = New XmlDocument() BodyDoc.LoadXml(aaaa) Dim ReaderDoc As XmlNodeReader = New XmlNodeReader(BodyDoc) 'TENTAR METER NO DATASET Dim ds As DataSet = New DataSet() ds.ReadXml(ReaderDoc) ReaderDoc.Close() dtTasks.Rows.Add() dtTasks.Rows(count).Item("NAME") = ds.Tables("RegistrationInfo").Rows(0).Item("URI").ToString dtTasks.Rows(count).Item("STATE") = taskState.ToString Dim column As DataColumnCollection = ds.Tables("Exec").Columns If column.Contains("Arguments") Then dtTasks.Rows(count).Item("ARGS") = ds.Tables("Exec").Rows(0).Item("Arguments").ToString Else dtTasks.Rows(count).Item("ARGS") = "" End If count = count + 1 Next End If Return dtTasks End Function 显然是一个数组,但您需要使用其中一种更新方法将文档推送到items数组,建议 { {3}} ,如

userCart

答案 1 :(得分:0)

由于adeneo指出userCart是一个数组,因为您正在使用find方法。但显然你需要找到一个由其userID给出的文档,所以建议使用findOne()代替。

此外,您需要保存文档,以便实际反映更改。

查看下面的更新代码:

router.post('/add-to-cart', function(req, res, next) {
  Cart.findOne({ userId: req.body.userID }, function(err, userCart){
      if(err) return next(err);
      console.log("TEST: "+JSON.stringify(userCart));
      var myItem = {itemID: req.body.itemId, quantity: 1}
      userCart.items.push(myItem);
      userCart.save(function(err, usersCart) {
           if(err) return next(err);
           res.send(usersCart);
      })
   })
});

希望这会有所帮助。

答案 2 :(得分:0)

可以使用以下方法解决此问题:

router.post('/add-to-cart', function(req, res, next) {
  Cart.findOne({ userID: req.body.userID }).then(function(userCart){
      console.log("TEST: "+JSON.stringify(userCart));
      const a = req.body.items;
      for(i=0;i<a.length;i++)
      {
        userCart.items.push(req.body.items[i]);
      }
      res.send(userCart);
   }).catch(next);
});