简体   繁体   English

如何使用猫鼬根据用户ID保存文档?

[英]How to save document based on user id using mongoose?

I am trying to save template based on user id , How can i make sure when template save it save with user id _id ? 我正在尝试根据用户ID保存模板,如何确保在保存模板时使用用户ID _id保存模板? i added reference to the templateSchema for User . 我为User添加了对templateSchema引用。

user.model.js user.model.js

var UserSchema = new mongoose.Schema({
  _id: { type: String, required: true, index: {unique: true}},
  firstName: String,
  lastName: String,
  type: String,
  groups:[{type: String, ref: 'Group', required: false}]
},
  {
    toObject: {
      virtuals: true
    },
    toJSON: {
      virtuals: true
    }
  });

export default mongoose.model('User', UserSchema);

template.model.js template.model.js

var User = require('../user/user.model.js');

var TemplateSchema = new mongoose.Schema({
  _id: { type: String, required: true},
  name: String,
  id: String,
  appliesTo: [],
  properties: [],
  createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User'}
 });


export default mongoose.model('Templates', TemplateSchema);

template.controller.js template.controller.js

var eTemplate = require('./template.model');

export function create(req, res) {
  console.log(req.body);
  eTemplate.createAsync(req.body)
    .then(responseWithResult(res, 201))
    .catch(handleError(res));
}

Mongoose has two built-in functions that are called before (pre) and after (post) you save a document. 猫鼬有两个内置函数,分别在保存文档之前(之前)和之后(之后)调用。 My advice is to make use of them. 我的建议是利用它们。 Here is an example of my code in which I search for an sequence number before saving the user document. 这是我的代码示例,其中我在保存用户文档之前搜索序列号。 You can do the same: When you save the template, make a request for the user id to the database (Or vice-versa). 您可以执行以下操作:保存模板时,向数据库请求用户ID(反之亦然)。 You can even save one, get the id and save the other. 您甚至可以保存一个,获取ID并保存另一个。

Bellow follows my code for the sequence and the user. 贝娄遵循我的序列和用户代码。

var UserSchema   = new Schema({
username: { type: String, required: true, unique: true },
id: { type: String },
...
});

UserSchema.pre('save', function(next) {
  let doc = this;     
  let id = 'userSeq'    

  Sequence.findByIdAndUpdate(id, { $inc : {nextSId : 1} },  function(error,data) {         
    if(error)
      next(error)               
    doc.id = data.nextSId-1;
    next();
  })        
});

I hope my answer was useful for you. 希望我的回答对您有用。 Just a remark, pre and post are not called in the event of updates for the document. 只是备注,在更新文档时不会调用前和后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM