我有两个模型:Document
和URL
:
const DocumentSchema = new Schema({
text: String,
path: String,
urls: [{ type: Schema.Types.ObjectId, ref: 'URL' }],
});
const URLSchema = new Schema({
url: String,
display_url: String,
ref: Boolean,
});
我想从数组中创建多个文档,所以我要做的是:
const documents = [{ ..., urls: [ ... ] }, ...];
Document.create(documents, (err, docs) => {
...
});
然后我收到错误urls: Cast to Array failed for value
。我想这是因为我想添加网址,但我还没有将它们添加到数据库中(所以我没有ID)。
有没有办法创建一个Schema,所以我可以添加它们而不先创建URL? (所以它们会自动添加?)
答案 0 :(得分:1)
您可以使用cascade
文档中间件在save
上实施Document
。您可以在URL
保存的输出中看到 const Schema = mongoose.Schema;
const DocumentSchema = new Schema({
text: String,
path: String,
urls: [{ type: Schema.Types.ObjectId, ref: 'URL' }],
});
const URLSchema = new Schema({
url: String,
display_url: String,
ref: Boolean,
});
const URL = mongoose.model('URL', URLSchema, 'urls');
DocumentSchema.pre('save', function(next){
URL.insertMany(this.urls, function(err, res){
if(err) throw err;
next();
})
});
const Document = mongoose.model('Document', DocumentSchema, 'documents');
var u1 = new URL({url : 'www.google.com'});
var d = new Document({text: 'test text', urls : [u1]})
d.save(function(err, doc){
console.log(doc)
})
也保存到集合
mongoose middleware documentation
saravana@ubuntu:~/node-mongoose$ node so2.js
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Mongoose: urls.insertMany([ { __v: 0, _id: 5a5b345f98f048281d88eac1, url: 'www.google.com' } ], {})
Mongoose: documents.insert({ text: 'test text', _id: ObjectId("5a5b345f98f048281d88eac2"), urls: [ ObjectId("5a5b345f98f048281d88eac1") ], __v: 0 })
{ __v: 0,
text: 'test text',
_id: 5a5b345f98f048281d88eac2,
urls: [ { url: 'www.google.com', _id: 5a5b345f98f048281d88eac1 } ] }
^C
saravana@ubuntu:~/node-mongoose$
输出
{{1}}