我在node.js中使用mongoose进行服务器设置。我遇到的问题是,当我按如下方式更新数据库时
Questions.update({id:questionID}, {$push: {answers: {answer:answer,answeredBy:username}}}, callback);
我看到数据已添加到MongoCompass中,但是当我使用
查询时Questions.find({tags:interests},callback);
不会返回更新的数据。但是,如果我重新启动服务器并再次查询,我会收到更新的结果。
如果我只使用.save
方法和查询保存数据和查询,则会更新数据库。
所以问题必须与我的.update
方法一致吗?我真的找不到我做错了什么
我的数据库如下
let mongoose =new require('mongoose');
const uuidv4 = require('uuid/v4');
//Define a schema
let Schema = mongoose.Schema;
let QuestionsSchema = new Schema({
id: {
type: String,
unique: true
},
title: String,
details: String,
askedDate: {type: Date, default: Date.now},
tags: [{
type: String
}],
askedBy: String,
answers: [{
answeredBy: String,
answer: String,
answeredDate: {type: Date, default: Date.now}
}]
});
let Questions = module.exports = mongoose.model('Questions', QuestionsSchema);
module.exports.addQuestion = function (newQuestion, callback) {
//generating a new random id for each question
newQuestion.id = uuidv4();
newQuestion.save(callback);
};
module.exports.addAnswer = function (username,answer, questionID, callback) {
Questions.update({id:questionID}, {$push: {answers: {answer:answer,answeredBy:username}}}, callback);
};
module.exports.getQuestions = function (interests, callback) {
Questions.find({tags:interests},callback);
};
方法如下调用
Questions.getQuestions(user.tags[i], function (err, questions) {
if (err) {
let output = {
error: {
status: "fail",
name: err.name,
message: err.message,
text: err.toString()
}
};
let statusCode = err.status || 500;
res.json(output);
res.send();
}
else {
questions.map((data) => {
if (!sentTags.includes(data.id)) {
jsonResponse.push(data);
sentTags.push(data.id);
}
});
if (i === user.tags.length - 1) {
res.send(JSON.parse(JSON.stringify(jsonResponse)));
}
}
});
和
Questions.addAnswer(user.username,req.body.answer, req.body.id, function (err) {
if (err) {
let output = {
error: {
status: "fail",
name: err.name,
message: err.message,
text: err.toString()
}
};
let statusCode = err.status || 500;
res.status(statusCode).json(output);
res.send();
}
else {
res.json({status: "success", message: "Answer Added"});
res.send();
}
});
答案 0 :(得分:0)
由于MongoDB最终是一致的,如果问题被保存,然后立即更新,可能会发生变化尚未完全传播的情况。
在Mongoose中,尝试指定“' primary'有了这个:
Questions.find({tags:interests}).read('p').exec(callback)
How to specify read concerns in Mongoose
MongoDB Read Concern documentation
根据用例的不同,您可能还想探讨写问题: