【问题标题】:Mongoose not saving data to mongodb猫鼬不将数据保存到 mongodb
【发布时间】:2013-12-08 11:07:54
【问题描述】:

我想记录每次计算,但 cal.save() 没有在 mongodb 中注册数据对象。目前它只是阻碍我的猫鼬模块):任何愿意看我简单代码的好心人。

# Import library files
restify         = require 'restify'
mongoose        = require 'mongoose'

# Create schema for recording calculations
calculationSchema = new mongoose.Schema
    action: String
    firstNumber: Number
    secondNumber: Number
    timeStamp: 
        type: Date
        default: Date.now

Calculation = mongoose.model 'calculation', calculationSchema

# Start and verify mongodb connection
mongoose.connect 'mongodb://localhost/test' 
db = mongoose.connection
db.on 'error', console.error.bind console, 'connection error:'
db.once 'open', ->
    console.log "Successfully connected to MongoDB"


# Create API server to listen to requests
server = restify.createServer()

# Create GET API that capture all params in the urls
server.get '/calculate/:action/:firstNum/:secondNum', (req, res, next) ->
    action = req.params.action
    firstNum = parseFloat req.params.firstNum
    secondNum = parseFloat req.params.secondNum

    # Create Calculation object
    cal = new Calculation
        action: action
        firstNumber: firstNum
        secondNumber: secondNum

    cal.save (err, cal) ->
        # Handle Errors
        if err then console.log 'Erorr in saving calculation'

    res.send 200

另外,为了检查它是否被保存,我去了终端并输入了 mongo,然后输入了 db.calculation.find() 但没有出现):

【问题讨论】:

  • 这有什么问题?
  • 哦,不,我漏掉了那部分。它 mongodb 没有注册 cal.save() 方法。):

标签: node.js mongodb coffeescript mongoose


【解决方案1】:

Mongoose 将您的小写模型名称复数,以确定要使用的集合。所以你需要查看calculations 集合。

db.calculations.find() 

【讨论】:

  • @Junhao 不要,它会绊倒很多人,这是作者承认的错误,但我们坚持下去。
猜你喜欢
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 2016-06-20
  • 2020-01-26
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
相关资源
最近更新 更多