如何在Mongoose中保存对另一个文档的引用? [英] How do you save a reference to another document in Mongoose?

查看:121
本文介绍了如何在Mongoose中保存对另一个文档的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文档保存到数据库,该数据库包含对另一个文档的引用.

I want to save a document to the database, which contains a reference to another document.

但是,当我发布文档时,Mongoose用其他方式替换了我发送的_id.

However, when I POST the document, Mongoose replaces the _id I send it, with something else.

这是我的猫鼬代码(在Express中)

Here's my Mongoose code (in 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);

这是我要发送到服务器的代码,例如:

And here's the code I'm sending to the server, for example:

var results = {
    round: 555ec731385b4d604356d8e5,
    selection: 10,
    time: 19
};

但是在数据库中,它以不同的round ID出现.例如,结果像

But in the database, it appears with a different round ID. For example, it comes out like

{ selection: 10,
  time: 19,
  round: 5573ef74536a1e58489e59c4,
  _id: 5573ef74536a1e58489e59c5 }

为什么会这样?

在使用Mongoose构建Web应用程序时,保存对另一个文档的引用的合适方法是什么?

What is the proper to save a reference to another document, when building a web app with Mongoose?

推荐答案

猫鼬为子文档添加了_id字段.

mongoose added a _id field for sub document.

要取消此操作,请为您的架构添加ID假:

to cancel it, add id false for your schema:

schemas.round_results = new mongoose.Schema({
    _id:false,
    round: {type: mongoose.Schema.ObjectId, ref: 'Round'},
    selection: Number,
    time: Number
});
var Round_Results = mongoose.model("Round_Results", schemas.round_results);

这篇关于如何在Mongoose中保存对另一个文档的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆