MongooseJS-如何保存文档和参考文档 [英] MongooseJS - How to save document and referenced document

查看:76
本文介绍了MongooseJS-如何保存文档和参考文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Request.findOne({_id: id}).populate("user").exec(function(err, request) {
    if (!err) {
        request.user.firstname = firstname;
        request.date = date;
        request.save(next);
    }

保存后,日期已更改,但用户的名字未更改.
型号:

After save, date has changed but the user's firstname has not.
Model :

  var Request = new Schema({
    user: {
        type: ObjectId,
        ref: 'User',
        required: true
    },
    date: {
        type: Date,
        default: Date.now()
    },

我仍然可以这样做

     request.user.save(function(err){
        if(!err)
            request.save(next)
     });

但是第一个为什么不起作用?

But why doesn't the first one work ?

推荐答案

检查猫鼬的更新引用"部分

Check the 'Updating Refs' section of the Mongoose documentation on populate.

在示例中,您将在此处看到仍然必须保存已创建的RequestUser文档. (在示例中,他们首先保存了用户'guille',然后在回调中保存了'story'.)

You will see there, in the example, that you still must save both the Request and User documents you have created. (In the example, they first save the user 'guille' then in the callback they save the 'story'.)

在猫鼬中, SubDocs 会在父文档保存但.populate不执行此操作时保存

In Mongoose, SubDocs save when a parent doc saves but .populate does not do this.

这篇关于MongooseJS-如何保存文档和参考文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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