【发布时间】:2015-08-21 20:30:28
【问题描述】:
我想将一个文档保存到数据库中,其中包含对另一个文档的引用。
但是,当我发布文档时,Mongoose 将我发送的 _id 替换为其他内容。
这是我的 Mongoose 代码(在 Express 中)
var resultItem = new models.Round_Results({
selection: result.selection,
time: result.time,
round: mongoose.Types.ObjectId(result.round)
});
models.User.findOne({username: username}, function(err, user){
user.results.push(resultItem);
user.save(function(err, result){
...
});
});
这是架构:
schemas.round_results = new mongoose.Schema({
round: {type: mongoose.Schema.ObjectId, ref: 'Round'},
selection: Number,
time: Number
});
var Round_Results = mongoose.model("Round_Results", schemas.round_results);
这是我发送到服务器的代码,例如:
var results = {
round: 555ec731385b4d604356d8e5,
selection: 10,
time: 19
};
但在数据库中,它以不同的round ID 出现。例如,它像
{ selection: 10,
time: 19,
round: 5573ef74536a1e58489e59c4,
_id: 5573ef74536a1e58489e59c5 }
为什么会这样?
在使用 Mongoose 构建 Web 应用程序时,保存对另一个文档的引用的正确方法是什么?
【问题讨论】:
-
嗯!另一个文件?你的意思是不止一个?因为您当前的架构被定义为只有一个单一的引用。
-
我想保存一个
Round_Result,它引用了另一个文档——那个文档是Round
标签: node.js mongodb express mongoose