MongooseJS - 具有现有引用的Model.create

时间:2018-02-28 06:22:57

标签: javascript mongodb mongoose

我正在尝试使用model.create()简写来创建一个包含现有用户ObjectId的新公司。

const userSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
});

const companySchema = new mongoose.Schema({
    companyName: String,
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }]
});

const User = mongoose.model('user2', userSchema);
const Company = mongoose.model('company2', userSchema);

以下用户已存在于users集合

{"_id":"5a9633031fe445041c07afd3","firstName":"John","lastName":"Doe","__v":0}

现在我想与现有用户一起创建一家新公司:

Company.create({
  companyName: 'Foo, Inc.',
  users: {5a9633031fe445041c07afd3}
}).then(function(err, company) {
  console.log(err, company);
});

我尝试过用户的变体:

users: '5a9633031fe445041c07afd3'
users: [5a9633031fe445041c07afd3]
users: [{5a9633031fe445041c07afd3}]

如何保存此文档?

1 个答案:

答案 0 :(得分:0)

试试这个

let model = new Company();
const body = {
    companyName: 'Foo, Inc.',
    users: "5a9633031fe445041c07afd3"
};
model = Object.assign(model, body);
model.then((company) => {
    console.log(company);
}).catch((err) => {
    console.log(err);
})