我想将计数器的值存储在MongoDB数据库中。在服务器创建时,我需要获得此计数器值。如果数据库为空,我创建一个文档并返回它,否则我获取文档。
问题是count
方法是异步的。在发布快递时,myCounter
的值仍为null
。我应该如何修改此代码以创建myCounter
?
import express from 'express'
import mongoose, { Schema } from 'mongoose'
mongoose.connect('mongodb://localhost/test')
var CounterSchema = new Schema({ value: Number })
CounterSchema.methods.increment = function (cb) { this.value++; this.save() }
var Counter = mongoose.model('Counter', CounterSchema)
var myCounter = null
Counter.count({}, (err, count) => {
if (err) { return }
if (!count) {
myCounter = Counter({value: 0})
return
}
if (count > 1) { return }
Counter.findOne({}, {}, {}, (err, post) => {
if (err) { return }
myCounter = post
})
})
console.log(myCounter) // Is still null :(
var app = express()
app.get('/', (req, res) => {
myCounter.increment() // Error if the request is quickly sent after the server start
res.json(myCounter.value)
})
app.listen(3000)
答案 0 :(得分:-1)
您可以尝试这样
import express from 'express'
import mongoose, { Schema } from 'mongoose'
mongoose.connect('mongodb://localhost/test')
var CounterSchema = new Schema({ value: Number })
CounterSchema.methods.increment = function (cb) { this.value++ }
var Counter = mongoose.model('Counter', CounterSchema)
console.log(myCounter) // Is still null :(
var myCounter = null
var app = express()
app.listen(3000,async () => {
await Counter.count({}, (err, count) => {
if (err) { return }
if (!count) {
myCounter = Counter({value: 0})
return
}
if (count > 1) { return }
Counter.findOne({}, {}, {}, (err, post) => {
if (err) { return }
instance = post
})
})
app.get('/', (req, res) => {
myCounter.increment()
res.json(myCounter.value)
})
})
这里我们在异步创建服务器之后立即分配myCounter变量,我们使用 await 关键字使代码同步工作。